Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Socket Server
#1
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]
Reply
#2
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?
Reply
#3
You probably forgot to link libws2_32 to your project.
Reply
#4
what about WSACleanup()... not good mayne.
Reply
#5
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple in progress socket library Nightly 3 1,676 02-14-2012, 08:12 AM
Last Post: AceInfinity

Forum Jump:


Users browsing this thread: 1 Guest(s)