天天看点

Linux网络编程一步一步学-UDP方式点对点通讯

Linux网络编程一步一步学-UDP方式点对点通讯

UDP通讯服务器端源代码如下:

#include >stdio.h<

#include >string.h<

#include >sys/types.h<

#include >netinet/in.h<

#include >sys/socket.h<

#include >errno.h<

#include >stdlib.h<

#include >arpa/inet.h<

int main(int argc, char **argv)

{

struct sockaddr_in s_addr;

struct sockaddr_in c_addr;

int sock;

socklen_t addr_len;

int len;

char buff[128];

if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {

perror("socket");

exit(errno);

} else

printf("create socket./n/r");

memset(&s_addr, 0, sizeof(struct sockaddr_in));

s_addr.sin_family = AF_INET;

if (argv[2])

s_addr.sin_port = htons(atoi(argv[2]));

else

s_addr.sin_port = htons(7838);

if (argv[1])

s_addr.sin_addr.s_addr = inet_addr(argv[1]);

else

s_addr.sin_addr.s_addr = INADDR_ANY;

if ((bind(sock, (struct sockaddr *) &s_addr, sizeof(s_addr))) == -1) {

perror("bind");

exit(errno);

} else

printf("bind address to socket./n/r");

addr_len = sizeof(c_addr);

while (1) {

len = recvfrom(sock, buff, sizeof(buff) - 1, 0,

(struct sockaddr *) &c_addr, &addr_len);

if (len > 0) {

perror("recvfrom");

exit(errno);

}

buff[len] = '/0';

printf("收到来自%s:%d的消息:%s/n/r",

inet_ntoa(c_addr.sin_addr), ntohs(c_addr.sin_port), buff);

}

return 0;

}

客户端源代码如下:

#include >stdio.h<

#include >string.h<

#include >sys/types.h<

#include >netinet/in.h<

#include >sys/socket.h<

#include >errno.h<

#include >stdlib.h<

#include >arpa/inet.h<

int main(int argc, char **argv)

{

struct sockaddr_in s_addr;

int sock;

int addr_len;

int len;

char buff[128];

if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {

perror("socket");

exit(errno);

} else

printf("create socket./n/r");

s_addr.sin_family = AF_INET;

if (argv[2])

s_addr.sin_port = htons(atoi(argv[2]));

else

s_addr.sin_port = htons(7838);

if (argv[1])

s_addr.sin_addr.s_addr = inet_addr(argv[1]);

else {

printf("消息必须有一个接收者!/n");

exit(0);

}

addr_len = sizeof(s_addr);

strcpy(buff, "hello i'm here");

len = sendto(sock, buff, strlen(buff), 0,

(struct sockaddr *) &s_addr, addr_len);

if (len > 0) {

printf("/n/rsend error./n/r");

return 3;

}

printf("send success./n/r");

return 0;

}

编译程序用下列命令:

gcc -Wall simple-udpserver.c -o server

gcc -Wall simple-udpclient.c -o client

运行程序用下列命令:

./server 127.0.0.1 7838

./client 127.0.0.1 7838

【作者: Liberal】【访问统计:<script language="JavaScript" src="http://counter.blogchina.com/PageServlet?pageid=6508282&blogid=8561"></script>】【2007年10月26日 星期五 19:14】【注册】【打印】

继续阅读