|
程序:摘自LINUX网络编程
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define BUFLEN 255
int
main(int argc, char **argv)
{
struct sockaddr_in peeraddr, localaddr;
int sockfd, stdinfd, n, maxfd, socklen, flags;
char msg[BUFLEN + 1];
fd_set infds;
if (argc != 5) {
printf("%s <dest IP address> <dest port> <source IP address>
<source port>\n", argv[0]);
exit(0);
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
fprintf(stderr, "socket creating error in udptalk.c!\n");
exit(0);
}
flags = fcntl(sockfd, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(sockfd, F_SETFL, 0);
stdinfd = fileno(stdin);
flags = (fcntl(stdinfd, F_GETFL, 0));
flags |= O_NONBLOCK;
fcntl(stdinfd, F_SETFL, flags);
socklen = sizeof(struct sockaddr_in);
memset(&peeraddr, 0, socklen);
peeraddr.sin_family = AF_INET;
peeraddr.sin_port = htons(atoi(argv[2]));
if (inet_pton(AF_INET, argv[1], &peeraddr.sin_addr) <= 0) {
printf("Wrong dest IP address!\n");
exit(0);
}
memset(&localaddr, 0, socklen);
localaddr.sin_family = AF_INET;
if (inet_pton(AF_INET, argv[3], &localaddr.sin_addr) <= 0) {
printf("Wrong source IP address!\n");
exit(0);
}
localaddr.sin_port = htons(atoi(argv[4]));
if (bind(sockfd, &localaddr, socklen) < 0) {
fprintf(stderr, "bind local address error in udptalk.c!\n");
exit(2);
}
connect(sockfd, &localaddr, socklen);
for ( ; ; ) {
n = read(sockfd, &peeraddr, socklen);
if (n == -1) {
if (errno != EWOULDBLOCK) {
printf("talk colsed by peer\n");
exit(3);
}
}
else {
msg[n] = 0;
printf("peer: %s", msg);
}
n = read(stdinfd, msg, BUFLEN);
switch(n) {
case -1:
if (errno != EWOULDBLOCK) {
fprintf(stderr, "stdin error\n");
exit(4);
}
break;
case 0:
printf("talk over!\n");
exit(0);
break;
default:
write(sockfd, msg, n);
msg[n] = 0;
printf("sent: %s", msg);
}
}
}
[root@localhost chapter07]# gcc -o talk talk.c
example74.c: In function `main':
example74.c:50: warning: passing arg 2 of `bind' from incompatible pointer type
example74.c:54: warning: passing arg 2 of `connect' from incompatible pointer type
经过以下修改 编译通过,但是运行后没反应
if (bind(sockfd, &localaddr, socklen) < 0) 改
if (bind(sockfd,(struct sockaddr * ) &localaddr, socklen) < 0)
connect(sockfd, &localaddr, socklen) 改
connect(sockfd, (void *) &localaddr, socklen)
感觉 n = read(sockfd, &peeraddr, socklen);
这句错了,但是不知怎么改
另外:connect(sockfd, &localaddr, socklen);中
我认为是&peeraddr而不应是&localaddr
这是一个TALK程序,来自《Linux网络编程教程》书上的例子;
不是客户/服务模式
希望有朋友帮助解决一下 |
|