Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1256719
  • 博文数量: 404
  • 博客积分: 10011
  • 博客等级: 上将
  • 技术积分: 5382
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-03 16:29
文章存档

2010年(40)

2009年(140)

2008年(224)

我的朋友

分类: LINUX

2009-05-25 10:44:33

客户端

#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MYPORT 4950 /* the port users will be sending to */

int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in their_addr; /* connector's address information */
struct hostent *he;
int numbytes;
if(argc != 3)
{
   fprintf(stderr,"usage: talker hostname message\n");
   exit (1);
}

if((he=gethostbyname(argv[1])) == NULL)
{ /* get the host info */
   herror("get host by name" );
   exit(1);
}

if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
   perror("socket");
   exit( 1 );
}

their_addr.sin_family = AF_INET; /* host byte order */
their_addr.sin_port = htons(MYPORT); /* short, network byte order */
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(their_addr.sin_zero), 8); /* zero the rest of the struct */

if((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1)
{
   perror("send to" );
   exit(1);
}

printf("sent %d bytes to %s\n",numbytes,inet_ntoa(their_addr.sin_addr));
close(sockfd);

return 0;
}

服务端:

#include
#include
#include
#include
#include
#include
#include
#include
#define MYPORT 4950 /* the port users will be sending to */
#define MAXBUFLEN 100

main()
{
int sockfd;
struct sockaddr_in my_addr; /* my address information */
struct sockaddr_in their_addr; /* connector's address information */
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; /* host byte order */
my_addr.sin_port = htons(MYPORT); /* short, network byte order */
my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
bzero(&(my_addr.sin_zero), 8); /* zero the rest of the struct */

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, 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);
}

运行方法:

1 编译    gcc -o server.exe server.c

gcc -o client.exe client.c

2 运行

先启动服务端    ./server.exe

再启动客户端   ./client IP|host messge    如:./client 202.114.46.213 hello

阅读(960) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~