|
楼主 |
发表于 2003-8-24 16:20:12
|
显示全部楼层
udp server
[code:1]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MYPORT 6789
#define TPORT 7000
#define MAXBUFLEN 100
int main(void)
{
int sockfd,tsockfd;
struct sockaddr_in my_addr; // my address information
struct sockaddr_in their_addr; // connector's address information
struct sockaddr_in ttheir_addr;
int addr_len, numbytes;
char buf[MAXBUFLEN];
if((sockfd = socket(AF_INET, SOCK_DGRAM,0)) == -1) {
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(my_addr.sin_zero), '\0', 8);
if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
addr_len = sizeof(struct sockaddr);
if ((numbytes=recvfrom(sockfd, buf, MAXBUFLEN-1, 0, (struct sockaddr *)&their_addr, &addr_len)) ==-1) {
perror("recvfrom");
exit(1);
}
printf("got packet from %s\n",inet_ntoa(their_addr.sin_addr));
printf("packet is %d bytes long\n",numbytes);
buf[numbytes] = '\0';
printf("packet contains \"%s\"\n",buf);
close(sockfd);
if((tsockfd=socket(AF_INET, SOCK_STREAM, 0))==-1) {
perror("socket");
exit(1);
}
ttheir_addr.sin_family = AF_INET;
ttheir_addr.sin_port=htons(TPORT);
ttheir_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&(ttheir_addr.sin_zero),'\0',8);
if(connect(tsockfd,(struct sockaddr *)&ttheir_addr, sizeof(struct sockaddr))==-1) {
perror("connect");
exit(-1);
}
if(send(tsockfd,buf,strlen(buf),0)==-1)
perror("send");
close(tsockfd);
exit(0);
printf("sendto %s\n",inet_ntoa(ttheir_addr.sin_addr));
close(tsockfd);
return 0;
}
[/code:1]
UDP间通信没有问题 就是UDP和TCP间有问题 能connect |
|