c ++ socket stream api

时间:2010-10-25 03:33:20

标签: c++ api class sockets stream

我正在使用看起来像这里的流套接字真正好的API: http://www.pcs.cnu.edu/~dgame/sockets/socketsC++/sockets.html

我无法访问已连接用户的IP,因为它是另一个类“ServerSocket”中使用的类“Socket”的私有成员。我的程序看起来就像演示它只是它的进程。

// libraries
#include <signal.h>
#include <string>
#include <iostream>

// headers
#include "serversocket.hpp"
#include "socketexception.hpp"
#include "config.hpp"

using namespace std;

void sessionHandler( ServerSocket );


int main ( int argc, char** argv )
{
    configClass config; // this object handles command line args
    config.init( argc, argv ); // initialize config with args

    pid_t childpid; // this will hold the child pid

    signal(SIGCHLD, SIG_IGN); // this prevents zombie processes on *nix

    try
    {
        ServerSocket server ( config.port ); // create the socket

        cout << "server alive" << "\n";
        cout << "listening on port: " << config.port << "\n";

        while ( true )
        {

            ServerSocket new_client; // create socket stream
            server.accept ( new_client ); // accept a connection to the server

            switch ( childpid = fork() ) // fork the child process
            {
            case -1://error
                cerr << "error spawning child" << "\n";
                break;
            case 0://in the child
                sessionHandler( new_client ); // handle the new client
                exit(0); // session ended normally
                break;
            default://in the server
                cout << "child process spawned: " << childpid << "\n";
                break;
            }
        }
    }
    catch ( SocketException& e ) // catch problem creating server socket
    {
        cerr << "error: " << e.description() << "\n";
    }

    return 0;
}


// function declarations

void sessionHandler( ServerSocket client )
{
    try
    {
        while ( true )
        {
            string data;
            client >> data;
            client << data;
        }
    }
    catch ( SocketException& e )
    {
        cerr << "error: " << e.description() << "\n";
    }
}

所以我的问题是,我是否可以访问当前连接到套接字的客户端的IP?如果必须针对该功能进行修改,那么最干净的方法是什么?

感谢您的建议

我能够添加这两个函数,这些函数只允许我从main的范围获取IP,如下所示:

server.get_ip(new_client); 但我真正喜欢的是得到像new_client.ip();

这是我的2个功能,也许你可以进一步帮助我:

std::string Socket::get_ip( Socket& new_socket )
{
  char cstr[INET_ADDRSTRLEN];
  std::string str;
  inet_ntop(AF_INET, &(m_addr.sin_addr), cstr, INET_ADDRSTRLEN);
  str = cstr;
  return str;
}

std::string ServerSocket::get_ip( ServerSocket& sock )
{
    return Socket::get_ip( sock );
}

1 个答案:

答案 0 :(得分:1)

您正在使用的Socket类具有私有数据成员:

sockaddr_in m_addr;

这包含连接到套接字的客户端的信息。您可以通过以下方式获取人类可读的地址:

char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(m_addr.sin_addr), str, INET_ADDRSTRLEN);

至于您需要进行的更改,请将m_addr公开(不推荐)或添加可以根据上述代码示例返回字符串的成员函数。