- 论坛徽章:
- 0
|
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#define BUFFER_SIZE 256
int main(int argc,char **argv)
{
int sockfd,sockfd2;
socklen_t socklen;
struct sockaddr_in servaddr,servaddr2;
int port,port2;
char msg[BUFFER_SIZE];
int n;
switch (argv[1][0]){
case '1':port = 20001;port2 = 2001;break;
case '2':port = 20002;port2 = 2002;break;
}
socklen = sizeof(servaddr);
sockfd = socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,socklen);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if(bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) == -1){
//error handle;
}
n = recvfrom(sockfd,msg,BUFFER_SIZE,0,(struct sockaddr *)&servaddr,&socklen);
write(STDOUT_FILENO, msg,strlen(msg));
close(sockfd);
if((sockfd2 = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("create socket error!\n");
exit(1);
}
bzero(&servaddr2,sizeof(servaddr2));
servaddr2.sin_family = AF_INET;
inet_aton("127.0.0.1",&servaddr2.sin_addr);
servaddr2.sin_port = htons(port2);
int kkk;
if( (kkk = connect(sockfd2,(struct sockaddr*)&servaddr2,socklen)) < 0)
{
printf("can`t connect to %d %d \n",port2,kkk);
exit(1);
}
n = read(sockfd2,msg,BUFFER_SIZE);
write(STDOUT_FILENO, msg,strlen(msg));
write(sockfd2,msg,strlen(msg));
close(sockfd2);
}
如上代码,udp接收报文的部分可以正常执行,但是之后tcp连接的部分就会在connect的时候出错
但是如果把udp接受报文的部分注释掉,tcp连接的部分则没有错误。。
哪位老大知道是什么原因? |
|