都是新建个socket
然后
客户端是connect +write+read
服务端是bind+while (read +write)
client:
server.c:
然后
客户端是connect +write+read
服务端是bind+while (read +write)
client:
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <string.h>
int main(){
char* echo_host="192.168.1.105";
int echo_port =7777;
int sockfd;
struct sockaddr_in *server=(struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
server->sin_family=AF_INET;
server->sin_port=htons(echo_port);
server->sin_addr.s_addr=inet_addr(echo_host);
sockfd=socket(AF_INET,SOCK_STREAM,0);
printf("Connected to %s\n\n",echo_host);
//-------------------上面相同------
printf("Numeric:%u\n",server->sin_addr);
connect(sockfd,(struct sockaddr*)server,sizeof(*server));
char* msg="hello world";
printf("\nSend:%s \n",msg);
write(sockfd,msg,strlen(msg));
char* buf=(char*)malloc(1000);
int bytes=read(sockfd,(void*)buf,1000);
printf("\nBytes res %u\n",bytes);
printf("\nBuff %s res\n",buf);
close(sockfd);
}
server.c:
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <string.h>
int main(){
char* echo_host="192.168.1.105";
int echo_port =7777;
int sockfd;
struct sockaddr_in *server=(struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
server->sin_family=AF_INET;
server->sin_port=htons(echo_port);
server->sin_addr.s_addr=inet_addr(echo_host);
sockfd=socket(AF_INET,SOCK_STREAM,0);
//-------------------上面相同--[color=red]-[/color]---
if(bind(sockfd,(struct sockaddr*)server,sizeof(*server))){
printf("bind failed\n");
}
listen(sockfd,SOMAXCONN);
int clientfd;
struct sockaddr_in* client=(struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
int client_size=sizeof(*client);
char* buf=(char*)malloc(1000);
int bytes;
printf("wait for connection to port %u\n",echo_port);
clientfd=accept(sockfd,(struct sockaddr*)client,&client_size);
//printf("Connected to %s:%u\n\n",inet_ntoa(client->sin_addr),ntohs(client->sin_port));
printf("Numeric:%u\n",ntohl(client->sin_addr.s_addr));
while(1){
bytes=read(clientfd,(void*)buf,1000);
if(bytes<=0){
close(clientfd);
printf("coneecton close\n");
exit(0);
}
printf("bytes received:%u\n",bytes);
printf("text %s\n",buf);
write(clientfd,buf,bytes);
}
}