Linux下的UDP Socket简单例子
(2013-01-23 13:33:13)
标签:
it |
客户端代码 client.c
intmain( int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
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");
char sendline[ 100];
sprintf(sendline, "Hello, world!" );
sendto(sockfd, sendline, strlen(sendline), 0, ( struct sockaddr *)&servaddr, sizeof(servaddr));
close(sockfd);
return 1;
}
intmain( int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons( 50001);
bind(sockfd, ( struct sockaddr *)&servaddr, sizeof(servaddr));
int n;
char recvline[ 1024];
recvfrom(sockfd, recvline, 1024, 0, NULL, NULL);
printf( "%s\n", recvline);
close(sockfd);
}
#include
<stdio.h>
#include
<string.h>
#include
<sys/socket.h>
#include
<netinet/in.h>
int
{
}
服务器端代码 server.c
#include
<stdio.h>
#include
<string.h>
#include
<sys/socket.h>
#include
<netinet/in.h>
int
{
}