linuxsocket程序
1. linux socket是什麼意思
基於Linux的SOCKET編程。
2. linux中socket是如何調用驅動程序
分為發送和接受:
發送:
首先,socketAPI會創建並把數據至一個叫sk_buff的結構體,然後依次把sk_buff交給運輸層,網路層,數據鏈路層協議進行處理,然後在填寫完sk_buff後再把他交付給驅動程序由網路設備發送出去。
接受和發送是反過程,驅動層程序一般由中斷處理收到數據包後會創建sk_buff結構體,讓後把數據和一些控制信息填進去,再把sk_buff向數據鏈路層協議交付,然後就是網路層,運輸層最後交給socketAPI介面了
3. linux下的socket編程
同學,你希望從哪個方面入手進行完善呢?或者說你遇到什麼問題?!!
你的程序健壯性是很不錯的,就是太復雜,我給個最簡單的。接收和顯示放一塊:
void read_and_echo(in fd)
{
char buf[512]={0};
int rc;
while (1)
{
rc=read(fd,buf,511);// 讀入511個字元
buf[rc]=0;// 截斷
printf("Reveive Message: %s",buf);
}
}
4. 在Linux系統下編寫一個socket程序
我給你一個更高端的
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <string.h>
#define M 8888
struct qun
{
int cy[5];
};
struct haoyou
{
int py[5];
};
struct ri
{
int geren[5];
};
int main()
{
struct qun group[5]={0};
struct haoyou pyd[5]={0};
struct ri ziji[5]={0};
printf("server onil\n");
printf("this port is %d\n",M);
fd_set rest;
int servsock=socket(AF_INET,SOCK_STREAM,0);
if(-1==servsock)
{
perror("socket perror");
return 1;
}
struct sockaddr_in servaddr;
struct sockaddr_in clienaddr;
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(M);
int a=bind(servsock,(struct sockaddr *)&servaddr,sizeof(servaddr));
if(-1==a)
{
perror("bind perror\n");
return 1;
}
int b=listen(servsock,5);
if(-1==b)
{
perror("listen perror");
return 1;
}
FD_ZERO(&rest);
char sendbuff[1024];
char recvbuff[1024];
int n;
int qw;
int r[10];
int min[1024]={0};
int i=0;
int iWho[10]={0};
int mabi[1024]={0};
char mingzi[10][50]={0};
char caonima[1024]={0};
int wocao[10]={0};
n=sizeof(clienaddr);
struct timeval time;
while(1)
{
time.tv_sec = 0;
time.tv_usec = 470;
FD_SET(servsock,&rest);
FD_SET(fileno(stdin),&rest);
select(servsock+1,&rest,NULL,NULL,&time);
if(FD_ISSET(servsock,&rest))
{
r[i]=accept(servsock,(struct sockaddr *)&clienaddr,&n);
if(r[i]==-1)
{
i--;
}
i++;
}
int p;
for(p=0;p<i;p++)
{
FD_SET(r[p],&rest);
}
int ret=select(r[i-1]+1,&rest,NULL,NULL,&time);
if(ret<0)
{
printf("socket error\n");
continue;
}
else
{
int u;
for(u=0;u<i;u++
5. linux編程socket程序的編譯語句
server端:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAX_LINE 100
int main()
{
struct sockaddr_in server;
struct sockaddr_in client;
int server_fd;
int client_fd;
socklen_t len;
char buf[MAX_LINE]; //用於存儲傳送內容到緩沖區
char addr_ip[INET_ADDRSTRLEN];//存儲客戶端地址緩沖區
int port = 8000;//埠號8000
int n; //讀寫位元組數
bzero(&server,sizeof(server));//清空地址結構
server.sin_family = AF_INET;//使用ipv4
server.sin_addr.s_addr = INADDR_ANY;//伺服器可以接受任意地址
server.sin_port = htons(port);//把埠號轉成網路位元組序
server_fd = socket(AF_INET,SOCK_STREAM,0);//創立套接字,使用tcp協議
bind(server_fd,(struct sockaddr *)&server,sizeof(server));//將地址和套接字綁定
listen(server_fd,10);//開始監聽
printf("waiting```\n");
while(1)
{
client_fd = accept(server_fd,(struct sockaddr *)&client,&len);
n = read(client_fd,buf,MAX_LINE);//讀取客戶端來的消息
inet_ntop(AF_INET,&client.sin_addr,addr_ip,sizeof(addr_ip));
printf("client ip is : %s , port is : %d\n",addr_ip,ntohs(client.sin_port));
printf("content is : %s\n",buf);//列印客戶端信息
write(client_fd,buf,n);//轉發回去給客戶端
close(client_fd);
}
if(close(client_fd) == -1)
{
perror("fail to close");
exit(1);
}
return 0;
}
client端:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAX_LINE 100
int main(int argc,char * argv[])
{
struct sockaddr_in server;//伺服器地址
char buf[MAX_LINE];
int server_fd;
int port = 8000;
char *str = "test string";//默認字元串
if(argc > 1)
{
str = argv[1];//從命令參數中取得用戶輸入的串
}
bzero(&server,sizeof(server));//清空地址結構
server.sin_family = AF_INET;//使用ipv4
inet_pton(AF_INET,"192.168.228.129",&server.sin_addr);
server.sin_port = htons(port);
server_fd = socket(AF_INET,SOCK_STREAM,0);//創建套接字
connect(server_fd,(struct sockaddr *)&server,sizeof(server));
write(server_fd,str,strlen(str) + 1);
//因為是本機測試,所以不用考慮延時
read(server_fd,buf,MAX_LINE);
printf("recieve from server :%s\n",buf);
close(server_fd);
return 0;
}
//源碼來自於網路,誰寫也都類似,都是基於tcp的三次握手協議來寫的
6. linux socket程序 求代碼運行結果
ret=write(socket_fd,send_buff,strlen(send_buff));
應該改為:
ret=write(new_socket_fd,send_buff,strlen(send_buff));
accept成功後,所有的操作,都要針對新獲得的句柄來操作,不然會引發錯誤,造成主程序異常退出。
7. 在linux下如何用c語言來寫一個socket編程的聊天小程序
源碼如下:
//chat_one.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <malloc.h>
#include <sys/select.h>
int main( int argc, char **argv)
{
struct sockaddr_in chatone, chattwo;
char pmsg[1000];
char *buf;
int chatone_fd;
int ret,i;
int len, msg_len;
fd_set fdset;
if ( argc < 2 ){
printf("please input ip address\n");
return -1;
}
printf("server address is %s\n", argv[1]);
chattwo.sin_family = AF_INET;
chattwo.sin_port = htons(60002);
inet_pton(AF_INET, argv[1], &chattwo.sin_addr.s_addr);
chatone.sin_family = AF_INET;
chatone.sin_port = htons(60000);
chatone.sin_addr.s_addr = INADDR_ANY;
chatone_fd = socket(PF_INET, SOCK_DGRAM, 0);
if ( -1 == chatone_fd ){
printf("create socket failed %s\n", strerror(errno));
return -1;
}
ret = bind(chatone_fd, (struct sockaddr *)&chatone, sizeof(chatone));
if ( -1 == ret){
printf("bind failed %s \n", strerror(errno));
return -1;
}
for(i=0; i<1000;i++){
FD_ZERO( &fdset );
FD_SET ( 0, &fdset);
FD_SET( chatone_fd, &fdset);
if ( -1 == select ( chatone_fd+1, &fdset, NULL, NULL, NULL) ){
continue;
}
if ( FD_ISSET( chatone_fd, &fdset)){
recvfrom( chatone_fd, pmsg, 999, 0, NULL, 0);
printf("receive %s\n", pmsg);
}
else{
memset( pmsg, 0, 1000);
fgets(pmsg, 999, stdin);
len = sizeof(chattwo);
sendto( chatone_fd, pmsg, 1000, 0,\
(struct sockaddr*) &chattwo, len);
printf("send %s\n", pmsg);
}
}
printf("sent %d packets\n", i);
close(chatone_fd);
return 0;
}
//chat_two.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <malloc.h>
#include <sys/select.h>
int main( int argc, char **argv)
{
struct sockaddr_in chatone, chattwo;
char pmsg[1000];
char *buf;
int chattwo_fd;
int ret,i;
int len, msg_len;
fd_set fdset;
if ( argc < 2 ){
printf("please input ip address\n");
return -1;
}
printf("server address is %s\n", argv[1]);
chattwo.sin_family = AF_INET;
chattwo.sin_port = htons(60002);
chattwo.sin_addr.s_addr = INADDR_ANY;
chatone.sin_family = AF_INET;
chatone.sin_port = htons(60000);
inet_pton(AF_INET, argv[1], &chatone.sin_addr.s_addr);
chattwo_fd = socket(PF_INET, SOCK_DGRAM, 0);
if ( -1 == chattwo_fd ){
printf("create socket failed %s\n", strerror(errno));
return -1;
}
ret = bind(chattwo_fd, (struct sockaddr *)&chattwo, sizeof(chattwo));
if ( -1 == ret){
printf("bind failed %s \n", strerror(errno));
return -1;
}
for(i=0; i<1000;i++){
FD_ZERO( &fdset );
FD_SET ( 0, &fdset);
FD_SET( chattwo_fd, &fdset);
if ( -1 == select ( chattwo_fd+1, &fdset, NULL, NULL, NULL) ){
continue;
}
if ( FD_ISSET( chattwo_fd, &fdset)){
recvfrom( chattwo_fd, pmsg, 999, 0, NULL, 0);
printf("receive: %s\n", pmsg);
}
else{
memset( pmsg, 0, 1000);
fgets(pmsg, 999, stdin);
len = sizeof(chatone);
sendto( chattwo_fd, pmsg, 1000, 0,\
(struct sockaddr*) &chatone, len);
printf("send %s\n", pmsg);
}
}
printf("sent %d packets\n", i);
close(chattwo_fd);
return 0;
}
編譯好這個兩個程序就可以進行簡單的通信了。
8. linux socket 的程序如何在windows下編譯並運行
本質區別是這樣的,linux下用的是伯克利socket,windows底下用的WinSocket.
兩者其實是大同小異的,不同的地方在以下幾點:
1 頭文件不同,在linux下用到的關鍵頭文件<sys/socket.h>
windows下用到的是 <Winsock2.h>
2 socket的初始化不一樣,在windows下要有一個WSAStartup,而linux 下沒有。
3 具體的細節不一樣,linux下的c和windows下的c的一些語法有些出入,你自己找找。
下面我把windows下的socket通訊的最基本的結構給你,你對照著修改就可以了,一下的程序我調試了一下,編譯過了。
客戶端
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}
SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
char recvBuf[100];
recv(sockClient,recvBuf,100,0);
printf("%s\n",recvBuf);
send(sockClient,"This is lisi",strlen("This is lisi")+1,0);
closesocket(sockClient);
WSACleanup();
}
伺服器端
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
listen(sockSrv,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
while(1)
{
SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
char sendBuf[100];
sprintf(sendBuf,"來自伺服器端",
inet_ntoa(addrClient.sin_addr));
send(sockConn,sendBuf,strlen(sendBuf)+1,0);
char recvBuf[100];
recv(sockConn,recvBuf,100,0);
printf("%s\n",recvBuf);
closesocket(sockConn);
}
}
9. 求linux下的socket 編程
看這個代碼你最好了解一下tcp協議,了解一下三次握手機制,要不然你可能看不懂,當初我們學到這的時候學了一天的tcp....還有,就是把下面代碼分開放到2個.c文件中,必須先運行伺服器端,再運行客戶端
//伺服器端的代碼
1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/socket.h>
4 #include <unistd.h>
5 #include <netinet/in.h>
6 #include <sys/stat.h>
7 #include <stdlib.h>
8 #include <arpa/inet.h>
9
10 #define LOCAL_PORT 1234
11 #define MAX_LEN 512
12 #define MAX_NUM 5
13
14 int main(int argc, char *argv[])
15 {
16 int sock_fd, sock_data;
17 int ret, len_addr;
18 char buf[MAX_LEN];
19 ssize_t len;
20 struct sockaddr_in local_addr, remote_addr;
21
22 sock_fd = socket(AF_INET, SOCK_STREAM, 0); //創建套接字,sock_fd是套接字描述符,類似我們的身份證號碼
23 if (sock_fd < 0)
24 {
25 perror("socket()");
26 return sock_fd;
27 }
28
29 local_addr.sin_family = AF_INET;// 協議族,ipv4
30 local_addr.sin_port = htons(LOCAL_PORT);// 把伺服器埠轉換成網路位元組序
31 local_addr.sin_addr.s_addr = inet_addr("127.0.0.1");//把字元串形式的ip轉換成網路位元組序
32
33 ret = bind(sock_fd, (struct sockaddr *)&local_addr, (size_t)sizeof(local_addr));// 把sock_fd和本機ip,埠邦定
34 if (ret < 0)
35 {
36 perror("bind()");
37 close(sock_fd);
38 return ret;
39 }
40
41 ret = listen(sock_fd, MAX_NUM);//監聽socket
42 if (ret)
43 {
44 perror("listen()");
45 close(sock_fd);
46 return ret;
47 }
48
49 memset(buf, 0, MAX_LEN);
50
51 len_addr = sizeof(remote_addr);
52
53 sock_data = accept(sock_fd, (struct sockaddr *)&remote_addr, (socklen_t *)&len_addr);//接受客戶端的連接
54 if (ret < 0)
55 {
56 perror("accept()");
57 close(sock_fd);
58 return ret;
59 }
60
61 while (1)
62 {
63 int slen;
64 len = recv(sock_data, buf, MAX_LEN, 0);//接受客戶端的數據
65 if (len < 0)
66 {
67 perror("recv()");
68 close(sock_data);
69 close(sock_fd);
70 return len;
71 }
72 printf("%s\n", buf);
73
74 slen = send(sock_data, "congratulation!", 15, 0);//向客戶端發送數據
75 if (slen <= 0)
76 {
77 printf("slen = %d\n", slen);
78 perror("send()");
79 close(sock_data);
80 close(sock_fd);
81 return slen;
82 }
83 sleep(1);
84 }
85
86 close(sock_data);
87 close(sock_fd);
88
89 return 0; }
//客戶端代碼
1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/socket.h>
4 #include <unistd.h>
5 #include <netinet/in.h>
6 #include <sys/stat.h>
7 #include <stdlib.h>
8 #include <arpa/inet.h>
9
10 #define REMOTE_PORT 1234
11 #define MAX_LEN 512
12
13 int main(int argc, char *argv[])
14 {
15 int sock_fd, ret;
16 int len;
17 char buf[MAX_LEN];
18 struct sockaddr_in local_addr, remote_addr;
19
20 sock_fd = socket(AF_INET, SOCK_STREAM, 0);
21 if (sock_fd < 0)
22 {
23 perror("socket()");
24 return sock_fd;
25 }
26
28 local_addr.sin_family = AF_INET;
29 local_addr.sin_addr.s_addr = htonl(INADDR_ANY); //自動獲取本機的ip地址
30 local_addr.sin_port = htons(0); //隨機選取可用的埠,並不是指定埠為0
31
33 remote_addr.sin_family= AF_INET;
34 remote_addr.sin_port = htons(REMOTE_PORT);
35 ret = inet_aton("127.0.0.1", &remote_addr.sin_addr);
36
38 ret = bind(sock_fd, (struct sockaddr *)&local_addr, sizeof(local_addr)); //把本機的ip,port和socket綁定
39 if (ret < 0)
40 {
41 perror("bind() !");
42 close(sock_fd);
43 return ret;
44 }
45
47 ret = connect(sock_fd, (struct sockaddr *)&remote_addr, (socklen_t)sizeof(remote_addr)); //把本機的socket和對方的port,ip建立連接
48 if (ret < 0)
49 {
50 perror("connect()");
51 close(sock_fd);
52 return ret;
53 }
54
55 memset(buf, 0, MAX_LEN);
56
57 while (1)
58 {
59 int i;
60 // len = send(sock_fd, buf, (size_t)MAX_LEN, 0);
61 len = send(sock_fd, "hello", 6, 0);
62 if (len <= 0)
63 {
64 perror("send()");
65 close(sock_fd);
66 return ret;
67 }
68
69 // printf("%d-->bytes send!\n", len);
70 sleep(1);
71
72 len = recv(sock_fd, buf, MAX_LEN, 0);
73 if (len <= 0)
74 {
75 perror("recv()");
76 close(sock_fd);
77 return ret;
78 }
79
80 for (i = 0; i < len; i++)
81 {
82 printf("%c", buf[i]);
83 }
84 printf("\n");
85 }
86
87 close(sock_fd);
88
89 return 0;
90 }
10. Linux socket編程
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
char *host_name="127.0.0.1";
int port=7778;
struct student
{
char name[20];
char num[20];
float score;
}t={"xiejian","200701415",89.9};
int main ( )
{
char buf[502];
int socket_descriptor;
struct sockaddr_in pin;
bzero(&pin,sizeof(pin));
pin.sin_family=AF_INET;
inet_pton(AF_INET,host_name,&pin.sin_addr);
pin.sin_port=htons(port);
if((socket_descriptor=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("Error openung socket!\n");
exit(1);
}
if(connect(socket_descriptor,(void *)&pin,sizeof (pin))==-1)
{
perror("can not connecting to server!\n");
exit (1);
}
printf("Send message to server ...\n");
//memset(buf,0,502);
//memcpy(buf,(void *)&t,sizeof(t));
//sprintf(buf,"%s %d",t.name,t.num);
//printf("the first string : %s\n",buf);
if(send(socket_descriptor,(void *) &t,sizeof(t),0)==-1)
{
perror("can not send message!\n");
exit (1);
}
printf("waiting for response from server!\n");
memset(buf,0,502);
if(recv(socket_descriptor,buf,sizeof(buf),0)==-1)
{
perror("can not receive response !\n");
exit (1);
}
printf("\n Response from server : \n");
memcpy((struct student *)&t,buf,sizeof(buf));
//printf("the string : %s \n",rebuf);
printf("--%s--%s--%5.1f--\n",t.name,t.num,t.score);
close (socket_descriptor);
}
/* 注意在send 結構體時應該把結構體強制類型轉換為void * 型
** 接受之後又要強制轉換回結構體型!否則則穿過來的是結構體的
** 一部分!
*/
下面是服務端
#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netdb.h>
int port=7778;
struct student
{
char name[20];
char num[20];
float score;
}t;
main()
{
struct sockaddr_in sin;
struct sockaddr_in pin;
int sock_descriptor;
int temp_sock_descriptor;
int size_of_addr;
//struct cfg a;
char buf[502];
int i,lenth;
sock_descriptor=socket(AF_INET,SOCK_STREAM,0);
if(sock_descriptor==-1)
{
perror("socket!\n");
exit(1);
}
bzero(&sin,sizeof(sin));
sin.sin_addr.s_addr=INADDR_ANY;
sin.sin_port=htons(port);
if(bind(sock_descriptor,(struct sockaddr *)&sin,sizeof (sin))==-1)
{
perror("bind!\n");
exit(1);
}
if(listen (sock_descriptor,20)==-1)
{
perror("listen!\n");
exit(1);
}
printf("Waiting for accepting connection from client!\n");
while(1)
{
printf("the process is waiting here!\n");
temp_sock_descriptor=accept(sock_descriptor, (struct sockaddr *)&pin,&size_of_addr);
if(temp_sock_descriptor==-1)
{
perror("call to accept!\n");
exit (1);
}
memset(buf,0,502);
if(recv(temp_sock_descriptor,buf,sizeof(buf),0)==-1)
{
perror("recv!\n");
exit (1);
}
printf("received : \n");
//printf("the recv buf is :%s\n",buf);
memcpy((struct student *) &t,buf,sizeof(buf));
printf("--%s--%s--%5.1f--\n",t.name,t.num,t.score);
if(send (temp_sock_descriptor,(void *) &t,sizeof(t),0)==-1)
{
perror("send!\n");
exit(1);
}
close (temp_sock_descriptor);
}
}