UDP套接字编程 - recvfrom()一个端口和sendto()其他端口

时间:2017-11-28 14:01:45

标签: c linux sockets

UDP套接字编程 - 服务器侦听端口5000 - 客户端侦听端口6000 recvfrom()来自一个港口 - 5000
sendto()到其他端口 - 6000到同一个客户端。

Server.c

#include <stdio.h>          /* for printf() and fprintf() */
#include <sys/socket.h>     /* for socket() and bind() */
#include <arpa/inet.h>      /* for sockaddr_in and inet_ntoa() */
#include <stdlib.h>         /* for atoi() */
#include <string.h>         /* for memset() */
#include <unistd.h>         /* for close() */

#define MAXSIZE 255         /* Longest string */
#define SRC_PORT 5000
#define DST_PORT 6000

int main(int argc, char *argv[])
{
    int sock;                               /* Socket */
    struct sockaddr_in ServAddr;        /* Local address */
    struct sockaddr_in ClntAddr;        /* Client address */
    socklen_t CliAddrLen;               /* Length of incoming message */
    char recBuffer[MAXSIZE];                /* Buffer for echo string */
    int recvMsgSize;                        /* Size of received message */ 
    int i;

    /* Create socket for sending/receiving datagrams */
    if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
        DieWithError("socket() failed");

    /* Construct local address structure */
    memset(&ServAddr, 0, sizeof(ServAddr));         /* Zero out structure */
    ServAddr.sin_family = AF_INET;                      /* Internet address family */
    ServAddr.sin_addr.s_addr = htonl(INADDR_ANY);       /* Any incoming interface */
    ServAddr.sin_port = htons(SRC_PORT);            /* Local port */

    /* Construct address structure */
    memset(&ClntAddr, 0, sizeof(ClntAddr));         /* Zero out structure */
    ClntAddr.sin_family = AF_INET;                      /* Internet address family */
    ClntAddr.sin_addr.s_addr = inet_addr("192.168.1.*");        
    ClntAddr.sin_port = htons(DST_PORT);            


    /* Bind to the local address */
    if (bind(sock, (struct sockaddr *) &ServAddr, sizeof(ServAddr)) < 0)
        DieWithError("bind() failed");

    for (;;) /* Run forever */
    {
        printf("Listening on UDP:5000 \n");
        /* Set the size of the in-out parameter */
        cliAddrLen = sizeof(ClntAddr);

        /* Block until receive message from a client */
        if ((recvMsgSize = recvfrom(sock,  recBuffer, MAXSIZE, 0,(struct sockaddr *) &ClntAddr, &cliAddrLen)) < 0)
            DieWithError("recvfrom() failed") ;

        printf("Handling Client: %s\n", inet_ntoa(ClntAddr.sin_addr));



            printf("Received Data: %s",recBuffer);
        printf("\n");

        /* Send response datagram back to the client */


        if (sendto(sock,  recBuffer, MAXSIZE, 0, (struct sockaddr *) & ClntAddr, sizeof(ClntAddr)) < 0)
            DieWithError("sendto() failed");

    }
    /* NOT REACHED */ 
}

完美无缺。客户端和服务器编程使用不同的端口来发送和接收数据。 谢谢 此致

1 个答案:

答案 0 :(得分:0)

这是错误的

lntAddr.sin_addr.s_addr = inet_addr("CLIENT_IP"); 

inet_addr采用虚线ip地址而不是主机名