首先,测试环境为linux虚拟机和我的开发板ARM7开发板,
首先是服务器程序:
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#define SERVPORT 8087 /*port */
#define BACKLOG 20/* max client */
int main()
{
printf("Main Start!\n");
int sockfd,client_fd;
struct sockaddr_in my_addr; /* loacl */
struct sockaddr_in remote_addr;
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)//AF_INET代表IPv4 Internet协议,SOCK_STREAM代表Tcp连接
,提供序列化的、可靠的、双向连接的字节流。支持带外数据传输。
函数socket()的第3个参数用于制定某个协议的特定类型,
通常某协议中只有一种特定类型,这样参数仅能设置为0;
但是有些协议有多种特定的类型,就需要设置这个参数来选择特定的类型。
{
printf("socket fail!\n");
perror("socket fail!"); exit(1);
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
{
printf("bind error!\n");
perror("bind error!");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
printf("listen error!\n");
perror("listen error!");
exit(1);
}
while(1) {
sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size)) == -1) {
printf("accept error!\n");
perror("accept error");
continue;
}
printf("REC FROM: %s\n",inet_ntoa(remote_addr.sin_addr)); //函数功能:将网络地址转换成“.”点隔的字符串格式
if (fork() == 0) {
if (send(client_fd, "Make Your idea Real! \n", 26, 0) == -1)
printf("send error!\n");
perror("send error!");
close(client_fd);
exit(0);
}else
close(client_fd);
}
}
然后是客户端程序
#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>
#define SERVPORT 3333
#define MAXDATASIZE 100 /*max client */
int main(int argc, char *argv[]){
int sockfd, recvbytes;
char buf[MAXDATASIZE];
struct hostent *host;
struct sockaddr_in serv_addr;
if (argc < 2) {
fprintf(stderr,"Please enter the server's hostname!\n");
exit(1);
}
if((host=gethostbyname(argv[1]))==NULL) {
herror("gethostbyname error!");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket create error!");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(SERVPORT);
serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(serv_addr.sin_zero),8);
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1) {
printf("connect error!\n");
perror("connect error!");
exit(1);
}
if ((recvbytes=recv(sockfd, buf, MAXDATASIZE, 0)) ==-1) {
printf("connect error2!\n");
perror("connect error!");
exit(1);
}
buf[recvbytes] = '\0';
printf("form server: %s",buf);
close(sockfd);
}
运行结果如下:
服务器
客户端: