首页 > 代码库 > Linux socket 测试
Linux socket 测试
Client : mini2440
Server : PC Ubuntu
网络的socket数据传输是一种特殊的I/O,socket也是一种文件描述符。socket也有一个类似于打开文件的函数:socket(),调用socket(),该函数返回一个整型的socket的描述符,随后的连接建立、数据传输等操作也都是通过该socket实现。此次测试用mini2440做Client,PC机做Server,同时连接上局域网。ping通之后,在mini2440上运行client.c,PC上运行server.c。
client.c :
#include <stdlib.h> #include <sys/types.h> #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main() { int cfd; int recbytes; int sin_size; char buffer[1024]={0}; struct sockaddr_in s_add,c_add; unsigned short portnum=0x8888; //port number cfd = socket(AF_INET, SOCK_STREAM, 0); if(-1 == cfd) { printf("socket fail ! \r\n"); return -1; } bzero(&s_add,sizeof(struct sockaddr_in)); s_add.sin_family=AF_INET; s_add.sin_addr.s_addr= inet_addr("172.20.21.247"); //IP of your PC s_add.sin_port=htons(portnum); printf("s_addr = %#x ,port : %#x\r\n",s_add.sin_addr.s_addr,s_add.sin_port); if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr))) { printf("connect fail !\r\n"); return -1; } printf("connect ok !\r\n"); if(-1 == (recbytes = read(cfd,buffer,1024))) { printf("read data fail !\r\n"); return -1; } buffer[recbytes]='\0'; printf("%s\r\n",buffer); getchar(); close(cfd); return 0; }server.c :
#include <stdlib.h> #include <sys/types.h> #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main() { int sfp,nfp; struct sockaddr_in s_add,c_add; int sin_size; unsigned short portnum=0x8888; //port number sfp = socket(AF_INET, SOCK_STREAM, 0); if(-1 == sfp) { printf("socket fail ! \r\n"); return -1; } printf("socket ok !\r\n"); bzero(&s_add,sizeof(struct sockaddr_in)); s_add.sin_family=AF_INET; s_add.sin_addr.s_addr=htonl(INADDR_ANY); s_add.sin_port=htons(portnum); if(-1 == bind(sfp,(struct sockaddr *)(&s_add), sizeof(struct sockaddr))) { printf("bind fail !\r\n"); return -1; } if(-1 == listen(sfp,5)) { printf("listen fail !\r\n"); return -1; } while(1) { sin_size = sizeof(struct sockaddr_in); nfp = accept(sfp, (struct sockaddr *)(&c_add), &sin_size); if(-1 == nfp) { printf("accept fail !\r\n"); return -1; } printf("waiting for %#x : %#x\r\n",ntohl(c_add.sin_addr.s_addr),ntohs(c_add.sin_port)); if(-1 == write(nfp,"hello,socket\r\n",32)) { printf("write fail!\r\n"); return -1; } printf("write ok!\r\n"); close(nfp); } close(sfp); return 0; }编译client.c: arm-linux-gcc -o client client.c 生成client可执行文件
编译server.c: gcc -o server server.c 生成server可执行文件
拷贝client到mini2440
PC机运行server:
root@desktop:~# ./server
socket ok !
mini2440运行client:
[root@FriendlyARM /sdcard] # ./client
s_addr = 0xf71514ac ,port : 0x8888
connect ok !
hello,socket
客户端已经收到了服务端发出的"hello,socket"的字符串
Linux socket 测试
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。