Linux下UDP的简单例子

//服务器端代码 server.c

#include <stdio.h>

#include <string.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <unistd.h>

#include <string.h>

#include <sys/types.h>

#include <arpa/inet.h>


int main(int argc, char **argv)

{

    struct sockaddr_in servaddr;

char recvline[1024];

    int sockfd = socket(PF_INET, SOCK_DGRAM, 0);

    

    //服务器 ip port


    bzero(&servaddr, sizeof(servaddr));

    servaddr.sin_family = AF_INET;

    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    servaddr.sin_port = htons(50001);

    

    //fcntl(sockfd, F_SETFL,O_NONBLOCK);//设置为非阻塞,根据具体需要决定是否需要非阻塞模式

    bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

    

    while(1)

    {

struct sockaddr_in addrClient;

int sizeClientAddr = sizeof(struct sockaddr_in);

        recvfrom(sockfd, recvline, 1024, 0, (struct sockaddr*)&addrClient,(socklen_t*)&sizeClientAddr);

char *pClientIP =inet_ntoa(addrClient.sin_addr);

        printf("%s-%d(%d) says:%s\n",pClientIP,ntohs(addrClient.sin_port),addrClient.sin_port, recvline);

    }

    close(sockfd);

}



//客户端代码 client.c

#include <stdio.h>

#include <string.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <unistd.h>

#include <string.h>

#include <sys/types.h>

#include <arpa/inet.h>


int main(int argc,char **argv)

{

   int sockfd = socket(PF_INET, SOCK_DGRAM, 0);

    //server ip port

   struct sockaddr_in servaddr;

   struct sockaddr_in client_addr;

   char sendline[100] = "hello world!";


    bzero(&servaddr,sizeof(servaddr));

    servaddr.sin_family = AF_INET;

    servaddr.sin_port = htons(50001);

    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    

    //my ip port (bind),也可以不绑定本地port,那么本地发送的port就是随机的。

    bzero(&client_addr,sizeof(client_addr));

    client_addr.sin_family = AF_INET;

    client_addr.sin_port = htons(40001);

    client_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    

    //client发出的udp包就是从这个port发出

   if(bind(sockfd, (struct sockaddr *)&client_addr,sizeof(client_addr))<0)

    {

        printf("video rtcp bind ret < 0\n");

    }

    sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr *)&servaddr,sizeof(servaddr));

    

    close(sockfd);

    

   return 1;

}



你可能感兴趣的:(Linux下UDP的简单例子)