- 论坛徽章:
- 0
|
用UDP传输数据
本地的客户端和服务端收发没问题,但是用对方机子发过来recvfrom无法接收,但是tcpdump可以嗅探到数据发过来了!
不知道问题何在啊,
服务端代码如下
[/code]
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERV_PORT 8866
#define MAXLINE 1024
int main(int argc, char **argv)
{
int sockfd;
int fd;
int num_recv;
socklen_t len;
char *recv_buf = malloc(MAXLINE);
struct sockaddr_in servaddr, cliaddr;
fd = open(argv[1],O_RDWR|O_TRUNC|O_CREAT); //打开文件
if(fd < 0){
perror("open file");
}else{
printf("open file success!\n");
}
sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //建立套接子
if(sockfd < 0){
perror("socket");
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET,"192.168.1.100",(struct sockaddr*)&servaddr.sin_addr.s_addr); //192.168.1.100是我的局域网IP
servaddr.sin_port = htons(SERV_PORT);
if(bind(sockfd, (struct sockaddr *) &servaddr,\
sizeof(servaddr))<0){
perror("bind");
}
printf("now begin recvie file \n");
for ( ; ; ) {
num_recv = recvfrom(sockfd, recv_buf, MAXLINE, 0, (struct sockaddr*)&cliaddr, &len); //接收
if(num_recv < 0){
perror("recvfrom");
}
printf("this time recved%d\n",num_recv);
write(fd,recv_buf,num_recv);
}
free(recv_buf);
close(fd);
return 0;
} |
|