标签:
Unix网络编程---第一次作业
要求:
客户端:从命令行读入服务器的IP地址;并连接到服务器;
服务器端: 接受客户的连接请求,并显示客户的IP地址和端口号。
实现代码:
1、客户端程序:my_client.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdio.h>
#define UPORT 8088 /*This is the port number used by me */
#define MAXLINE 256
int
main(int argc, char **argv)
{
int sockfd, n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if (argc != 2){
perror("usage: a.out <IPaddress>");
exit(-1);
}
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("socket error");
exit(-1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(UPORT); /* daytime server */
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
printf("inet_pton error for %s", argv[1]);
exit(-1);
}
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0){
perror("connect error");
exit(-1);
}
while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] =‘\0‘; // ‘\0‘ ASXII code is 0, so also can use 0;
if (fputs(recvline, stdout) == EOF){
perror("fputs error");
exit(-1);
}
}
if (n < 0)
perror("read error");
exit(0);
}
2、服务端程序:my_server.c
#include <sys/socket.h>
#include <sys/types.h>/*The funcion sizeof,socklen_t need*/
#include <netinet/in.h>/*The funcion sockaddr_in need*/
#include <unistd.h>
#include <arpa/inet.h>/*The funcion inet_ntoa need*/
#include <string.h>/*The funcion strlen need*/
#define UPORT 8088 /*This is the port number used by me */
#define MAXLINE 256
#define LISTENQ 32
int
main(int argc, char **argv)
{
int listenfd, connfd,reuse;
struct sockaddr_in servaddr, cliaddr;
char buff[MAXLINE];
socklen_t addrlen;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(UPORT); /* server port setting */
if( setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1){
perror("There is an error occured when the program set REUSEADDR symbol");
return -1;
}
if(bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr))==-1){
perror("%s\r\n","bind error");
exit(-1);
}
listen(listenfd, LISTENQ);
addrlen=sizeof(cliaddr);
for ( ; ; ) {
if((connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &addrlen))==-1){
perror("%s\r\n","An error occured while tring to creat a connfd! ");
exit(-1);
}
snprintf(buff, sizeof(buff), "%s %s:%d\r\n","The connection is successful, the ip address and port you are using are",inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port );
printf("the new connection address is:%s:%d\r\n", inet_ntoa(cliaddr.sin_addr), cliaddr.sin_port);
write(connfd, buff, strlen(buff));
//send(connfd,"ok\n",4,0);
close(connfd);
}
}
运行截图
编译:gcc my_client.c -o my_client
gcc my_server.c -o my_server
服务端运行:./my_server
客户端运行:./my_client 192.168.1.119
本实验是在两台虚拟机上操作,服务端ip为192.168.1.119,客户端ip为192.168.1.120
1、客户端:
2、服务端:
总结
1、 注意细节,免走弯路
2、 了解原理,举一反三
标签:
原文地址:http://www.cnblogs.com/lwhp/p/4990246.html