#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <cstdio>
using namespace std;
int main(int argc, char *argv[])
{
int port, n,sockfd;
struct sockaddr_in srv_addr;
struct hostent *serv;
char buffer[256];
if(argc<3)
{
cout <<"\n ussage: host port\nexiting\n";
return 0;
}
port=atoi(argv[2]);
sockfd=socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
cout <<"\nsocket creation on"<<port<<" failed\nexiting\ncheck to see if port is in use";
return 0;
}
serv = gethostbyname(argv[1]);
if (serv=NULL)
{
cout <<"\n"<<serv<<" is not a valid host name\nexiting";
return 0;
}
bzero((char *) &srv_addr, sizeof(srv_addr));
srv_addr.sin_family=AF_INET;
bcopy((char *) serv->h_addr,
(char *) &srv_addr.sin_addr.s_addr,
serv->h_length);
srv_addr.sin_port=htons(port);
if (connect(sockfd,&srv_addr,
sizeof (srv_addr))<0)
{
cout <<" \nconnection failed\n";
}
cout <<"\nType message\n";
bzero(buffer, 256);
cin.getline(buffer,256);
n=write(sockfd,buffer,strlen(buffer));
if (n>0)
{
cout <<"\nsocket write error\nexiting\n";
}
n=read(sockfd,buffer,255);
if (n>0)
{
cout <<"\nsocket read error\nexiting\n";
}
cout <<buffer;
return 0;
}
编译时,我收到此错误:
fg.c: In function ‘int main(int, char**)’:
fg.c:53:33: error: cannot convert ‘sockaddr_in*’ to ‘const sockaddr*’ for argument ‘2’ to ‘int connect(int, const sockaddr*, socklen_t)’
我无法弄明白。我是编程的菜鸟。任何帮助都很感激。
答案 0 :(得分:1)
你需要明确的演员。取代
connect(sockfd,&srv_addr, sizeof (srv_addr))
与
connect(sockfd,(sockaddr*)&srv_addr, sizeof (srv_addr))