服务端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
typedef struct sockaddr SockAddrStruct;
typedef struct sockaddr_in SockAddrStructIn;
int main()
{
char *Ip = "127.0.0.1";
int Port = 12345;
int SocketFd = -1;
int Fd = -1 ;
char Name[] = "server";
int Len = 0 ;
SockAddrStructIn Addr_in;
memset(&Addr_in, 0 , sizeof(Addr_in));
Addr_in.sin_family = AF_INET;
Addr_in.sin_port = htons(Port);
Addr_in.sin_addr.s_addr = inet_addr(Ip);
if( ( SocketFd = socket( AF_INET , SOCK_STREAM , 0 ) ) < 0 )
{
perror("socket create failed !\n");
return -1;
}
if( ( bind(SocketFd ,(SockAddrStruct* )&Addr_in , sizeof( Addr_in) ) ) < 0 )
{
perror("bind failed !\n");
return -1;
}
if( ( listen( SocketFd , 100 ) ) < 0 )
{
perror("listen failed !\n");
return -1;
}
write(STDOUT_FILENO, "server is start\n", sizeof("server is start\n"));
Len = sizeof(Addr_in);
if( ( Fd = accept(SocketFd,(SockAddrStruct* )&Addr_in,&Len) ) < 0 )
{
return -1 ;
}
char Msg[200] = {0};
char Buf[200] = {0};
while(1)
{
memset(Msg, 0 , sizeof(Msg));
memset(Buf, 0 , sizeof(Buf));
if( ( recv( Fd , Msg , sizeof(Msg) , 0 ) ) <= 0 )
{
perror("recv failed !\n");
return -1;
}
write(STDOUT_FILENO, Msg, sizeof(Msg));
snprintf(Buf,sizeof(Buf)-1,"%s:%s",Name,Msg);
if( write( Fd,Buf,sizeof(Buf)-1) < 0 )
{
perror("write Fd failed !\n");
return -1 ;
}
if( (write(STDOUT_FILENO, Buf, sizeof(Buf)-1))<0 )
{
perror("write STDOUT_FILENO failed !\n");
return -1;
}
}
return 0;
}
客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
typedef struct sockaddr SockAddrStruct;
typedef struct sockaddr_in SockAddrStructIn;
int main()
{
char *Ip = "127.0.0.1";
int Port = 12345;
int SocketFd = -1;
char Name[] = "zhouzhenhe";
SockAddrStructIn Addr_in;
memset(&Addr_in, 0 , sizeof(Addr_in));
Addr_in.sin_family = AF_INET;
Addr_in.sin_port = htons(Port);
Addr_in.sin_addr.s_addr = inet_addr(Ip);
if( ( SocketFd = socket( AF_INET , SOCK_STREAM , 0 ) ) < 0 )
{
perror("socket create failed !\n");
return -1;
}
if( (connect( SocketFd , (SockAddrStruct* )&Addr_in , sizeof( Addr_in) )) < 0 )
{
perror("connect failed !\n");
return -1;
}
char Msg[200] = {0};
char Buf[100] = {0};
while(1)
{
memset(Msg, 0 , sizeof(Msg));
memset(Buf, 0 , sizeof(Buf));
read(STDIN_FILENO , Buf , sizeof(Buf));
snprintf(Msg,sizeof(Msg)-1,"%s:%s",Name,Buf);
write(STDOUT_FILENO, Msg, sizeof(Msg));
write(SocketFd,Msg,sizeof(Msg));
memset(Msg, 0 , sizeof(Msg));
if( ( recv( SocketFd , Msg , sizeof(Msg) , 0 ) ) <= 0 )
{ perror("socket create failed !\n");
return -1;
}
write(STDOUT_FILENO, Msg, sizeof(Msg));
}
return 0;
}