server:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define backlog 10
int main(int argc,char **argv)
{
int serverfd;
int clientfd;
int ret;
int addrlen;
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
int clientnum = 0;
unsigned char recvbuf[1000];
int recvlen;
serverfd = socket(AF_INET, SOCK_STREAM, 0);
if(serverfd == -1)
{
printf("socket error\n");
return -1;
}
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(PORT);
s_addr.sin_addr.s_addr = INADDR_ANY;
memset(s_addr.sin_zero,0,8);
ret = bind(serverfd, (const struct sockaddr *)&s_addr,sizeof(struct sockaddr));
if(ret ==-1 )
{
printf("bind error\n");
return -1;
}
ret = listen(serverfd, backlog);
if(ret == -1)
{
printf("listen error\n");
return -1;
}
printf("waiting client connect......\n");
while(1)
{
addrlen = sizeof(struct sockaddr);
clientfd = accept(serverfd, (struct sockaddr *)&c_addr, &addrlen);
clientnum++;
if(clientfd != -1)
{
printf("connect client success: %d , %s \n",clientnum,inet_ntoa(c_addr.sin_addr));
if(!fork())
{
while(1){
recvlen = recv(clientfd, recvbuf, 999, 0);
if(recvlen <= 0){
printf("recv error\n");
close(clientfd);
return -1;
}else{
recvbuf[recvlen] = '\0';
printf("get the msg from client :%s\n",recvbuf);
}
}
}
}
}
close(serverfd);
return 0;
}
client.c:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#define PORT 8888
int main(int argc,char **argv)
{
int clientfd;
int ret;
struct sockaddr_in s_addr;
unsigned char sendbuf[1000];
int sendlen;
if (argc != 2) {
fprintf(stderr, "%s <dotted-address>\n", argv[0]);
exit(EXIT_FAILURE);
}
clientfd = socket(AF_INET, SOCK_STREAM, 0);
if(clientfd == -1)
{
printf("socket error\n");
return -1;
}
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(PORT);
if (inet_aton(argv[1], &s_addr.sin_addr) == 0) {
printf("server ip :%s \n",argv[0]);
return -1;
}
memset(s_addr.sin_zero,0,8);
ret = connect(clientfd, (struct sockaddr * )&s_addr,sizeof(struct sockaddr));
if(ret ==-1 )
{
printf("connect error\n");
return -1;
}
printf("connect success!!!\n");
while(1)
{
if(fgets(sendbuf, 9999, stdin)){
sendlen = send(clientfd, sendbuf, strlen(sendbuf), 0);
if(sendlen <= 0){
printf("send error\n");
close(clientfd);
return -1;
}
}
}
close(clientfd);
}
htons是将short型数据字节序由主机型转换为网络型,其实就是 将2字节数据的前后两个字节倒换,和对应的ntohs效果、实质相同,只不过名字不同。htonl和ntohl是 操作的4字节整形。将0x12345678变为0x78563412,名字不同,内容两两相同,一般情况下网络为大端, PPC的cpu为大端,x86的cpu为小端,arm的可以配置大小端,需要保证接收时字节序正确。
|