设置Ubuntu云服务器,C语言实现服务器单线程Socket UDP通讯

服务器端口为UDP

设置Ubuntu云服务器,C语言实现服务器单线程Socket UDP通讯_第1张图片

编写linux服务器软件,收到数据后,返回收到的数据:

#include
#include
#include
#include
#include
#include
#include
#include
 
#define MYPORT 1501
 
 
#define ERR_EXIT(m) \
    do { \
    perror(m); \
    exit(EXIT_FAILURE); \
    } while (0)
 
void echo_ser(int sock)
{
    char recvbuf[1024] = {0};
    struct sockaddr_in peeraddr;
    socklen_t peerlen;
    int n;
    printf("wait get data from port %d \n",MYPORT);
    while (1)
    {        
        peerlen = sizeof(peeraddr);
        memset(recvbuf, 0, sizeof(recvbuf));
        n = recvfrom(sock, recvbuf, sizeof(recvbuf), 0,(struct sockaddr *)&peeraddr, &peerlen);
        if (n <= 0)
        {            
            if (errno == EINTR)
                continue;
            printf("recvfrom error");
            ERR_EXIT("recvfrom error");
        }
        else if(n > 0)
        {
			printf("------------------------------------------------------------------------->>\n");
			unsigned int IP_peeraddr = ntohl(peeraddr.sin_addr.s_addr);
			printf("recvfrom IP:%d.%d.%d.%d  Port:%d\n",(IP_peeraddr>>24)&0xff,(IP_peeraddr>>16)&0xff,(IP_peeraddr>>8)&0xff,IP_peeraddr&0xff,ntohs(peeraddr.sin_port));
            printf("recvfrom data:%s --->> ",recvbuf);
			printf("sendto data:%s\n",recvbuf);
            sendto(sock, recvbuf, n, 0,(struct sockaddr *)&peeraddr, peerlen);

        }
    }
    close(sock);
}
 
int main(void)
{
    int sock;
    if ((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0){
        ERR_EXIT("socket error");
	}
    
    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(MYPORT);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    if (bind(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
        ERR_EXIT("bind error");
		printf("bind error,port is %d\n",MYPORT);
    }else{
		printf("bind success,port is %d\n",MYPORT);
	}
	unsigned int IP_servaddr = ntohl(servaddr.sin_addr.s_addr);
	printf("bind IP:%d.%d.%d.%d  Port:%d\n",(IP_servaddr>>24)&0xff,(IP_servaddr>>16)&0xff,(IP_servaddr>>8)&0xff,IP_servaddr&0xff,ntohs(servaddr.sin_port));

    echo_ser(sock);
    
    return 0;
}

 

你可能感兴趣的:(阿里云)