套接字:协议不支持错误

时间:2014-02-10 07:26:24

标签: linux sockets tcp

我目前正在使用Linux中的C语言进行Raw套接字编程。编译程序时,没有检测到错误。但是,在运行程序时,我得到“Socket:Protocol not supported”错误。我正在使用的代码如下。有人可以帮我找到解决问题的方法吗?

#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/tcp.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<netdb.h>
#define P 25

struct tcph {
unsigned short int th_sport;
unsigned short int th_dport;
 unsigned int th_seq;
 unsigned int th_ack;
 unsigned char th_x2:4, th_off:4;
 unsigned char th_flags;
 unsigned short int th_win;
 unsigned short int th_sum;
 unsigned short int th_urp;
};

int main()
{
 int sock,connected,bytes_recieved,true=1;
char send_data[1024],recv_data[1024];
struct sockaddr_in server_addr,client_addr;
int sin_size;

char datagram[4096];
struct tcph *tcph = (struct tcph *) datagram;
tcph->th_sport = htons (1234);
tcph->th_dport = htons (P);
tcph->th_seq = random ();
tcph->th_ack = 0;
tcph->th_x2 = 0;
tcph->th_off = 0;       
tcph->th_flags = 0; 
tcph->th_win = htonl (65535);   
tcph->th_sum = 0;
tcph->th_urp = 0;

if((sock=socket(AF_INET,SOCK_RAW,0))==-1)
{
perror("Socket");
exit(1);
}
if(setsockopt(sock,IPPROTO_TCP,IP_HDRINCL,&true,sizeof(true))==-1)
{
perror("Setsockopt");
exit(1);
}
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(9392);
server_addr.sin_addr.s_addr=INADDR_ANY;
bzero(&(server_addr.sin_zero),8);
if(bind(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1)
{
perror("Unable to bind");
exit(1);
}
if(listen(sock,5)==-1)
{
perror("Listen");
exit(1);
}
printf("\nTCP Server waiting for client on port 9392");
fflush(stdout);
while(1)
{
 sin_size=sizeof(struct sockaddr_in);
 connected=accept(sock,(struct sockaddr *)&client_addr,&sin_size);
 printf("\nI got a connection from (%s,%d)",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
 while(1)
{
printf("\nSEND (q or Q to quit):");
scanf("%s",send_data);
if(strcmp(send_data,"q")==0||strcmp(send_data,"Q")==0)
{
send(connected,send_data,strlen(send_data),0);
close(connected);
exit(0);
}
else
send(connected,send_data,strlen(send_data),0);
bytes_recieved=recv(connected,recv_data,1024,0);
recv_data[bytes_recieved]='\0';
if(strcmp(recv_data,"q")==0||strcmp(recv_data,"Q")==0)
{
close(connected);
break;
}
else
{
printf("\nRECIEVED DATA=%s",recv_data);
}
fflush(stdout);
}
}
close(sock);
return 0;
}

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

你可能想看看D.J.伯恩斯坦的tcpserver(见http://cr.yp.to/ucspi-tcp/tcpserver.html)。基本上,您可以在tcpserver下运行您的C程序,tcpserver将处理所有设置套接字,列出您正在使用的任何端口上的传入连接等等。当传入连接到达您指定的端口时, tcpserver将生成程序的一个实例,并将来自客户端的传入信息传递给程序的STDIN,并将来自程序STDOUT的传出信息传递回客户端。这样,你可以专注于你的程序的核心逻辑(并简单地读/写stdout / stdin),并让tcpserver处理所有繁重的任务,直到套接字等。