服务器端代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#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;
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_in myaddr, peeraddr;
if (argc < 3)
{
printf("input format is : %s <host_ip> <host_port>\n", argv[0]);
return -1;
}
{
printf("input format is : %s <host_ip> <host_port>\n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -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]);
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;
}
{
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);
// }
// {
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 <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#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;
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_in peeraddr;
if (argc < 3)
{
printf("input format is : %s <host_ip> <host_port>\n", argv[0]);
return -1;
}
{
printf("input format is : %s <host_ip> <host_port>\n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -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]);
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);
// }
//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;
}
}