How do I create RAW TCP/IP packets in C++?

后端 未结 11 1393
有刺的猬
有刺的猬 2020-12-24 06:59

I\'m a beginning C++ programmer / network admin, but I figure I can learn how to do this if someone points me in the right direction. Most of the tutorials are demonstrated

11条回答
  •  伪装坚强ぢ
    2020-12-24 08:06

    For TCP client side:

    Use gethostbyname to lookup dns name to IP, it will return a hostent structure. Let's call this returned value host.

    hostent *host = gethostbyname(HOSTNAME_CSTR);
    

    Fill the socket address structure:

    sockaddr_in sock;
    sock.sin_family = AF_INET;
    sock.sin_port = htons(REMOTE_PORT);
    sock.sin_addr.s_addr = ((struct in_addr *)(host->h_addr))->s_addr;
    

    Create a socket and call connect:

    s = socket(AF_INET, SOCK_STREAM, 0); 
    connect(s, (struct sockaddr *)&sock, sizeof(sock))
    

    For TCP server side:

    Setup a socket

    Bind your address to that socket using bind.

    Start listening on that socket with listen

    Call accept to get a connected client. <-- at this point you spawn a new thread to handle the connection while you make another call to accept to get the next connected client.

    General communication:

    Use send and recv to read and write between the client and server.

    Source code example of BSD sockets:

    You can find some good example code of this at wikipedia.

    Further reading:

    I highly recommend this book and this online tutorial:

    alt text

    4:

提交回复
热议问题