服务器端代码:
#include
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_in myaddr, peeraddr;
if (argc < 3)
{
printf("input format is : %s \n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -1;
}
myaddr.sin_family = PF_INET;
myaddr.sin_port = htons(atoi(argv[2]));
myaddr.sin_addr.s_addr = inet_addr(argv[1]);
if (bind(sockfd, (SA *)&myaddr, sizeof(myaddr)) == -1)
{
perror("bind fail");
return -1;
}
// while (1)
// {
addr_len = sizeof(peeraddr);
recvfrom(sockfd, buf, N, 0, (SA *)&peeraddr, &addr_len);
printf("recv from client:%s\n", buf);
strcat(buf, ": I am server");
sendto(sockfd, buf, N, 0, (SA *)&peeraddr, addr_len);
// }
return 0;
}
客户端代码如下:
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_in peeraddr;
if (argc < 3)
{
printf("input format is : %s \n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -1;
}
peeraddr.sin_family = PF_INET;
peeraddr.sin_port = htons(atoi(argv[2]));
peeraddr.sin_addr.s_addr = inet_addr(argv[1]);
strcpy(buf, "I am client");
//while (1)
// {
addr_len = sizeof(peeraddr);
sendto(sockfd, buf, N, 0, (SA *)&peeraddr, addr_len);
recvfrom(sockfd, buf, N, 0, (SA *)&peeraddr, &addr_len);
printf("recv from server:%s\n", buf);
// }
return 0;
}
阅读(872) | 评论(0) | 转发(1) |