UDP服务器的实现流程: 一、创建用户数据报套接字(socket函数): 通信域选择IPV4网络协议
、套接字类型选择数据报式
;
int sockfd = socket ( AF_INET, SOCK_DGRAM, 0 ) ;
二、填充服务器的网络信息结构体: 1.定义网络信息结构体变量; 2.求出结构体变量的内存空间大小; 3.结构体清零; 4.使用IPV4网络协议; 5.预留给在终端输入的网络字节序的端口号; 6.预留给在终端输入的IP地址;
struct sockaddr_in serveraddr;
socklen_t serveraddrlen = sizeof ( serveraddr) ;
memset ( & serveraddr, 0 , serveraddrlen) ;
serveraddr. sin_family = AF_INET;
serveraddr. sin_addr. s_addr = inet_addr ( argv[ 1 ] ) ;
serveraddr. sin_port = htons ( atoi ( argv[ 2 ] ) ) ;
三、套接字和服务器的网络信息结构体进行绑定(bind函数):
int ret = bind ( sockfd, ( struct sockaddr * ) & serveraddr, serveraddrlen) ;
四、接收来自客户端的数据(recvfrom函数)和给客户端发送应答消息(sendto函数):
int ret1 = recvfrom ( sockfd, buf, sizeof ( buf) , 0 , ( struct sockaddr * ) & clientaddr, & clientaddrlen) ;
strcat ( buf, "------------k" ) ;
int ret2 = sendto ( sockfd, buf, sizeof ( buf) , 0 , ( struct sockaddr * ) & clientaddr, clientaddrlen) ;
close ( sockfd) ;
# include
# include
# include
# include
# include
# include
# include
# include
# include
# define ERRLOG ( msg) do { \
printf ( "%s:%s:%d\n" , __FILE__ , __func__ , __LINE__ ) ; \
perror ( msg) ; \
exit ( - 1 ) ; \
} while ( 0 )
int main ( int argc, const char * argv[ ] )
{
if ( 3 != argc) {
printf ( "Usage : %s \n" , argv[ 0 ] ) ;
exit ( - 1 ) ;
}
int sockfd = socket ( AF_INET, SOCK_DGRAM, 0 ) ;
if ( - 1 == sockfd)
{
ERRLOG ( "socket error" ) ;
}
struct sockaddr_in serveraddr;
socklen_t serveraddrlen = sizeof ( serveraddr) ;
memset ( & serveraddr, 0 , serveraddrlen) ;
serveraddr. sin_family = AF_INET;
serveraddr. sin_addr. s_addr = inet_addr ( argv[ 1 ] ) ;
serveraddr. sin_port = htons ( atoi ( argv[ 2 ] ) ) ;
if ( - 1 == bind ( sockfd, ( struct sockaddr * ) & serveraddr, serveraddrlen) )
{
ERRLOG ( "bind error" ) ;
}
struct sockaddr_in clientaddr;
socklen_t clientaddrlen = sizeof ( clientaddr) ;
memset ( & clientaddr, 0 , clientaddrlen) ;
char buf[ 128 ] = { 0 } ;
while ( 1 )
{
memset ( buf, 0 , sizeof ( buf) ) ;
if ( - 1 == recvfrom ( sockfd, buf, sizeof ( buf) , 0 , ( struct sockaddr * ) & clientaddr, & clientaddrlen) )
{
ERRLOG ( "recvfrom error" ) ;
}
printf ( "客户端[%s:%d]发来数据[%s]\n" , inet_ntoa ( clientaddr. sin_addr) , ntohs ( clientaddr. sin_port) , buf) ;
strcat ( buf, "------------k" ) ;
if ( - 1 == sendto ( sockfd, buf, sizeof ( buf) , 0 , ( struct sockaddr * ) & clientaddr, clientaddrlen) )
{
ERRLOG ( "sendto error" ) ;
}
}
close ( sockfd) ;
return 0 ;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84