LINUX UDP网络编程

地址的转换:

主机字节序和网络字节序的转换函数,通常X86用的是大端格式,而网络是小端格式,所以在设定IP地址时要来一个转换

#include <netinet/in.h>

uint32_t htonl(uint32_t hostlong);

uint16_t htons(uint16_t hostshort);

uint32_t ntohl(uint32_t netlong);

uint16_t ntohs(uint16_t netshort);

 

#include <netinet/in.h>

#include <arpa/inet.h>

char *inet_ntoa(struct in_addr in);

in_addr_t inet_addr(const char *cp);

 

套接字的创建:

#include <sys/socket.h>

int socket(int domain, int type, int protocol);

成功返回0,失败返回-1

 

绑定端口:

#include <sys/socket.h>

int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);

成功返回0,失败返回-1

 

数据收发:

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,struct sockaddr *src_addr, socklen_t *addrlen);//一般会阻塞

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,const struct sockaddr *dest_addr, socklen_t addrlen);

 

UDP接收端编程流程:

调用socket创建套接字 =》调用bind绑定端口 =》循环调用recvfrom阻塞直到收到数据 =》调用close关闭套接字.

例:

int m_sock=socket(AF_INET,SOCK_DGRAM,0);

      if( -1 == m_sock)

      {

           perror("create receiver socket failed!");

           exit(1);

      }

      m_local_addr.sin_family = AF_INET;

      m_local_addr.sin_port = htons(5566);

      m_local_addr.sin_addr.s_addr = INADDR_ANY;

      if( -1 == bind(m_sock,(struct sockaddr*)&m_local_addr,sizeof(struct sockaddr)))

      {

           perror("bind failed!");

           exit(1);

      }

      struct sockaddr_in remoteaddr;

      int len=sizeof(struct sockaddr_in);

      char buf[100];

      memset(buf,0,100);

      receiver.recvfrom((void*)buf,100,(struct sockaddr*)&remoteaddr,(socklen_t*)&len);

      close(m_sock);

 

UDP发送端编程流程:

调用socket创建套接字 =》循环调用sendto发送数据 =》调用close关闭套接字.

例:

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

      if(-1 == sockfd)

      {

           perror("create socket error!");

           exit(1);

      }

      struct sockaddr_in remoteaddr;

      remoteaddr.sin_family=AF_INET;

      remoteaddr.sin_port=htons(5566);

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

      char buf[]="helloworld!";

      sendto(sockfd,buf,strlen(buf)+1,0,(struct sockaddr*)&remoteaddr,sizeof(struct sockaddr));

      close(sockfd);

你可能感兴趣的:(编程,linux,网络,socket,struct,domain)