我有一个需要连接到服务器的客户端应用程序。我对套接字编程的工作原理非常熟悉,但是不确定在尝试创建套接字时为什么会出现分段错误。
我有一个函数可以创建套接字。如果成功,它将继续连接到服务器。
if(socketClient::sock = socket(AF_INET,SOCK_STREAM,0) < 0);
return false;
int on = 1;
if (setsockopt(socketClient::sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1)
return false;
if(socketClient::connect("172.16.0.37", 50001))
{
socketClient::connected_ = true;
return true;
}
我已使用gdb确认创建套接字socket(AF_INET,SOCK_STREAM,0)
时抛出了分段错误
我现在很沮丧。我的代码编译时没有警告,并链接到可执行文件中。这可能是什么原因?
socketClient.h :(已过时)
#include <iostream>
#include "clientSocket.h"
#include <vector>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
#include <arpa/inet.h>
#include <vector>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <sys/sendfile.h>
#include <sys/stat.h>
#ifndef SOCKETCLIENT_H
#define SOCKETCLIENT_H
using namespace std;
class socketClient final
{
public:
socketClient(std::string, int);
~socketClient();
static bool connect(std::string, int);
private:
static int sock;
};
#endif // SOCKETCLIENT_H
完整程序:
// main.cpp
#include <cstdio>
#include "logger.h"
#include "startDaemon.h"
#include "hostFinder.h"
#include "localDatabase.h"
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/format.hpp>
#include "socketClient.h"
int main()
{
try
{
socketClient::connect("127.0.0.1", 50001);
}
catch (std::exception& e)
{
printf("We caught something bad");
return 0;
}
}
// socketClient.cpp
bool socketClient::connect(std::string hostName, int port)
{
std::string eMessage;
boost::format fmt;
try
{
sock = socket(AF_INET,SOCK_STREAM,0);
return true;
}
catch (std::exception& e)
{
fmt = boost::format("Process Shutdown: %s") % e.what();
eMessage = fmt.str();
logger::instance().log(eMessage, logger::kLogLevelError);
return false;
}
}
答案 0 :(得分:3)
https://www.binarytides.com/code-a-simple-socket-client-class-in-c/ 中的工作代码。您必须实现构造函数并创建类的实例。然后从此实例cf https://www.binarytides.com/code-a-simple-socket-client-class-in-c/调用connect()
static
不是必需的...
class :
/**
TCP Client class
*/
class tcp_client
{
private:
int sock;
std::string address;
int port;
struct sockaddr_in server;
public:
tcp_client();
bool conn(string, int);
bool send_data(string data);
string receive(int);
};
构造函数:
tcp_client::tcp_client()
{
sock = -1;
port = 0;
address = "";
}
方法:
/**
Connect to a host on a certain port number
*/
bool tcp_client::conn(string address , int port)
{
//create socket if it is not already created
if(sock == -1)
{
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
perror("Could not create socket");
}
cout<<"Socket created\n";
}
// [ ... ]
}
main.cpp
:
int main(int argc , char *argv[])
{
tcp_client c; // create instance
string host;
cout<<"Enter hostname : ";
cin>>host;
//connect to host
c.conn(host , 80); // invoke method
//[ ... ]
}
代码是来自https://www.binarytides.com/code-a-simple-socket-client-class-in-c/的不完整副本: