客户端:

点击(此处)折叠或打开

    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include


    #define REMOTEPORT 4567
    #define REMOTEIP "127.0.0.1"

    int main(int argc,char *argv[])
    {
    int s,len;
    struct sockaddr_in addr;
    int addr_len;
    char msg[256];
    int i=0;

    if((s=socket(AF_INET,SOCK_DGRAM,0))<0)
    {
    perror("error");
    exit(1);
    }
    else
    {
    printf("socket created.\n");
    printf("socket id : %d\n",s);
    printf("remote ip :%s\n",REMOTEIP);
    printf("remote port :%d\n",REMOTEPORT);
    }

    addr_len=sizeof(struct sockaddr_in);
    bzero(addr,sizeof(addr));
    addr.sin_family=AF_INET;
    addr.sin_port=htons(REMOTEPORT);
    addr.sin_addr.s_addr=inet_addr(REMOTEIP);

    while(1)
    {
    bzero(msg,sizeof(msg));
    len=read(STDIN_FILENO,msg,sizeof(msg));
    sendto(s,msg,len,0,addr,addr_len);
    printf("\nInput message : %s",msg);
    len=recvfrom(s,msg,sizeof(msg),0,addr,addr_len);
    printf("%d :",i);
    i ;
    printf("Received message: %s \n",msg);
    }
    }

服务器端:


点击(此处)折叠或打开

    #include
    #include
    #include
    #include
    #include
    #include

    #define LOCALPORT 4567

    int main(int argc,char *argv[])
    {
    int mysock,len;
    struct sockaddr_in addr;
    int addr_len;
    int i=0;
    char msg[256];

    if((mysock=socket(AF_INET,SOCK_DGRAM,0))<0)
    {
    perror("error:");
    exit(1);
    }
    else
    {
    printf("socket created.\n");
    printf("socket id : %d\n",mysock);

    }

    addr_len=sizeof(struct sockaddr_in);
    addr.sin_family=AF_INET;
    addr.sin_port=htons(LOCALPORT);
    addr.sin_addr.s_addr=htonl(INADDR_ANY);

    if(bind(mysock,addr,sizeof(addr))<0)
    {
    perror("connect:");
    exit(1);
    }
    else
    {
    printf("bind OK\n");
    printf("local port :%d\n",LOCALPORT);
    }

    while(1)
    {
    bzero(msg,sizeof(msg));
    len=recvfrom(mysock,msg,sizeof(msg),0,addr,addr_len);
    printf("%d:",i);
    i ;
    printf("message from:%s\n",inet_ntoa(addr.sin_addr));
    printf("message length:%d\n",len);
    printf("message :%s\n",msg);
    sendto(mysock,msg,len,0,addr,addr_len);
    }
    }


测试结果:实现本机上UDP通信,可以通过修改REMOTEIP,REMOTEPORT来实现自己想要的结果。