Support Forums
Socket Server - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Programming with C++ (https://www.supportforums.net/forumdisplay.php?fid=20)
+---- Thread: Socket Server (/showthread.php?tid=16194)



Socket Server - Scorch - 02-15-2011

Just posting this here. This is a server that justs waits for a connection from anything, even telnet.

Code:
#include <iostream>
#include <winsock2.h>

int main()
{
    WSAData wsadata;
    WORD Version = MAKEWORD(2, 1);

    WSAStartup(Version, &wsadata);

    SOCKADDR_IN ex;//struct child
    short length = sizeof(ex);

    SOCKET Listen = socket(AF_INET, SOCK_STREAM, NULL);//SOCK_STREAM is basically TCP while SOCK_DGRAM is UDP
    SOCKET Connect = socket(AF_INET, SOCK_STREAM, NULL);

    ex.sin_addr.s_addr = inet_addr("127.0.0.1");//ip address
    ex.sin_family = AF_INET;
    ex.sin_port = htons(100);//port, doesn't usually matter
    //Use htons() with sin_port for byte ordering

    bind(Listen,(SOCKADDR*)&ex, sizeof(ex));

    listen(Listen, SOMAXCONN);

    for(;;)
    {
        std::cout<<"Listening...";
        if(Connect = accept(Listen, (SOCKADDR*)&ex, (int*)&length))
        {
            std::cout<<"\nConnection accepted!\n";
            break;
        }
    }
    std::cin.get();
    return 0;
}

To test for a connection i'll use telnet. Windows xp users should have it by default.
Vistsa/7 users should go to control panel->programs and features->Turn on...-> Select telnet client.
[Image: Telnet.gif]


RE: Socket Server - Gaijin - 02-15-2011

Going to check this out soon, seems alright. Thanks for sharing.
I always had an Undefined Linker Reference to WSAStartup error when tried creating sockets. (or something smiliar)

Do you maybe know why a compiler would get that error, though I included all files that were needed?



RE: Socket Server - Scorch - 02-16-2011

You probably forgot to link libws2_32 to your project.


RE: Socket Server - Modest - 03-06-2011

what about WSACleanup()... not good mayne.


RE: Socket Server - Scorch - 03-07-2011

(03-06-2011, 11:50 AM)Modest Wrote: what about WSACleanup()... not good mayne.

I could, but it isn't really needed on something this small.