头文件
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
相关函数:
socket(); connect(); bind(); listen(); accept(); send(); recv(); close();
socket地址结构体struct sockaddr_in。
服务器端:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main()
{
int net_socket;
char server_msg[256]="this is msg from server\n";
net_socket = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bind(net_socket,(struct sockaddr *) &server_addr ,sizeof(server_addr));
listen(net_socket,5);
int client_socket;
client_socket = accept(net_socket,NULL,NULL);
send(client_socket,server_msg,sizeof(server_msg),0);
close(net_socket);
return 0;
}
客户端:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main()
{
int net_socket;
net_socket = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9000);
server_addr.sin_addr.s_addr = INADDR_ANY;
int connection_status = connect(net_socket,(struct sockaddr *) &server_addr ,sizeof(server_addr));
if (connection_status == -1)
{
printf("there was an error making a connection to the remote socket\n"); }
char server_response[256];
recv(net_socket,&server_response,sizeof(server_response),0);
printf("The server sent the data:%s\n",server_response);
close(net_socket);
return 0;
}