简体   繁体   English

创建套接字时出现分段错误

[英]Segmentation fault when creating socket

I have a client application that needs to connect to a server.我有一个需要连接到服务器的客户端应用程序。 I am pretty familiar with how socket programming works, but not sure why I would get a segmentation fault when trying to create a socket.我非常熟悉套接字编程的工作原理,但不确定为什么在尝试创建套接字时会出现分段错误。

I have a function that does the creation of the socket.我有一个函数来创建套接字。 If successful, it moves on to connect to the server.如果成功,它将继续连接到服务器。

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;
}

I have used gdb to confirm that the segmentation fault gets thrown when creating the socket socket(AF_INET,SOCK_STREAM,0)我已经使用 gdb 来确认创建套接字socket(AF_INET,SOCK_STREAM,0)时抛出分段错误socket(AF_INET,SOCK_STREAM,0)

I am pretty stumped at this point.我在这一点上很难过。 My code compiles without warnings and links into an executable fine.我的代码在没有警告的情况下编译并链接到可执行文件中。 What could be the reason for this?这可能是什么原因?

socketClient.h: (demessed) 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

Complete program:完整程序:

//main.cpp //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 //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;
    }
}

In https://www.binarytides.com/code-a-simple-socket-client-class-in-c/ is working code.https://www.binarytides.com/code-a-simple-socket-client-class-in-c/是工作代码。 You have to implement the constructor and create an instance of the class.您必须实现构造函数并创建类的实例。 Then invoke the connect() from this instance cf https://www.binarytides.com/code-a-simple-socket-client-class-in-c/ The static is not necessary ...然后从这个实例调用connect()参考https://www.binarytides.com/code-a-simple-socket-client-class-in-c/ 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);
};

constructor :构造函数

tcp_client::tcp_client()
{
    sock = -1;
    port = 0;
    address = "";
}

method :方法

/**
    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 : 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

    //[ ... ]
}

code is an incomplete copy from https://www.binarytides.com/code-a-simple-socket-client-class-in-c/ :代码是来自https://www.binarytides.com/code-a-simple-socket-client-class-in-c/的不完整副本:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM