服务器端代码
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h> int main( int argc, char *argv[] )
{
int sockfd, new_fd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int sin_size, portnumber;
const char hello[] = "Hello!\n";
if ( argc != )
{
printf("Usage: %s portnumber\a\n", argv[]);
exit();
} if ( (portnumber = atoi(argv[])) < )
{
printf("Usage: %s portnumber\a\n", argv[]);
exit();
} /* 服务器端创建socket */
if ( ( sockfd = socket(AF_INET, SOCK_STREAM, ) ) == )
{
printf("Socket Error !\n");
exit();
} /* 服务器端填充sockaddr结构 */
bzero( &server_addr, sizeof(struct sockaddr_in) );
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(portnumber); /* 将本地地址与socket绑定 */
if ( bind( sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr) ) == - )
{
printf("Bind Error!\n");
exit();
} /* 进入监听模式 */
if ( listen( sockfd, ) == )
{
puts("Listen Error!");
exit();
} while ()
{
/* 服务器阻塞,直到与客户端建立连接 */
sin_size = sizeof(struct sockaddr_in);
if ( (new_fd = accept(sockfd, (struct sockaddr *)(&client_addr), (socklen_t *)&sin_size ) ) == - )
{
puts("Accept Error!");
exit();
}
/* 连接成功 */
printf("Server get connection from %s\n", inet_ntoa(client_addr.sin_addr) );
inet_ntoa(client_addr.sin_addr);
if ( write( new_fd, hello, strlen(hello) ) == - )
{
puts("Write Error!");
exit();
} /* 本次通信结束,循环下一个 */
close(new_fd);
} /* 关闭当前连接 */
close(sockfd);
return ;
}
客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h> int main( int argc, char *argv[] )
{
int sockfd;
char buffer[];
struct sockaddr_in server_addr;
struct hostent *host;
int portnumber, nbytes;
if ( argc != )
{
printf("Usage: %s hostname portnumber\n", argv[] );
exit();
} if ( (host = gethostbyname(argv[])) == NULL )
{
puts("Host Error!");
exit();
} if ( (portnumber = atoi(argv[])) < )
{
printf("Usage: %s portnumber\a\n", argv[]);
exit();
} if ( ( sockfd = socket(AF_INET, SOCK_STREAM, ) ) == )
{
printf("Socket Error !\n");
exit();
} bzero( &server_addr, sizeof(struct sockaddr_in) );
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons( portnumber );
server_addr.sin_addr = *((struct in_addr *)host->h_addr); /* 与服务器建立连接 */
if ( connect( sockfd, (struct sockaddr *)(&server_addr), sizeof(server_addr) ) == - )
{
puts("Connect Error!");
exit();
} if ( (nbytes = read(sockfd, buffer, )) == - )
{
puts("Read Error!");
exit();
} buffer[nbytes] = '\0';
printf("I have received: %s\n", buffer );
close(sockfd);
return ;
}
运行结果