Linux 简单socket实现UDP通信

服务器端

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>

#define MAXLINE 80
#define SERV_PORT 8888

void do_echo( int sockfd, struct sockaddr *pcliaddr, socklen_t client )
{
    int n;
    socklen_t len;
    char mesg[80];
    while (1)
    {
        len = client;
        n = recvfrom( sockfd, mesg, 80, 0, pcliaddr, &len );
        sendto( sockfd, mesg, n, 0, pcliaddr, len );
        mesg[n] = 0;
        fputs( mesg, stdout );
    }
    return;
}

int main( void )
{
    int sockfd;
    struct sockaddr_in servaddr, cliaddr;
    sockfd = socket( AF_INET, SOCK_DGRAM, 0 );
    bzero( &servaddr, sizeof(servaddr) );
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);
    if ( bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1 )
    {
        perror("bind error");
        exit(1);
    }
    do_echo( sockfd, (struct sockaddr *)&cliaddr, sizeof(cliaddr) );
    return 0;
}

客户端

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MAXLINE 80
#define SERV_PORT 8888

void do_cli( FILE *fp, int sockfd, struct sockaddr *pservaddr, socklen_t servlen )
{
    int n;
    char sendline[MAXLINE], recvline[MAXLINE + 1];
    if ( connect( sockfd, (struct sockaddr *)pservaddr, servlen ) == -1 )
    {
        perror("connect error");
        exit(1);
    }

    while ( fgets(sendline, MAXLINE, fp ) != NULL )
    {
        write( sockfd, sendline, strlen(sendline) );
        n = read( sockfd, recvline, MAXLINE );
        if ( n == -1 )
        {
            perror("read error");
            exit(1);
        }
        recvline[n] = 0;
        fputs( recvline, stdout );
    }
    return;
}

int main( int argc, char **argv )
{
    int sockfd;
    struct sockaddr_in servaddr;
    if ( argc != 2 )
    {
        printf("usage: udpclient <IPaddress>\n");
        exit(1);
    }

    bzero( &servaddr, sizeof(servaddr) );
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);

    if ( inet_pton(AF_INET, argv[1], &servaddr.sin_addr ) <= 0 )
    {
        printf("[%s] is not a valid IPaddress\n", argv[1]);
        exit(1);
    }

    sockfd = socket(AF_INET, SOCK_DGRAM, 0 );
    do_cli( stdin, sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr) );
    return 0;
}

 

posted @ 2013-11-11 21:10  冰鸮  阅读(508)  评论(2编辑  收藏  举报