Post Reply 

Share on Facebook Share on Twitter

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Socket Server
Author Message
Scorch Offline
Intermediate C++

Trade Count: (0)
Posts: 83
Joined: Jan 2011
Reputation: 15
Post: #1
Socket Server
Here's a short socket example for C++. It listens then exits when a connection is found. Later I might make a client that sends and recieves messages.
/*This is a server, not a client.
Telnet will be the client.
By Scorch for Computertech*/
#include <iostream>
#include <winsock2.h>

int main()
    WSAData wsadata;
    WORD Version = MAKEWORD(2, 1);//This is the standard

    WSAStartup(Version, &wsadata);

    SOCKADDR_IN ex;//This has a struct called addr
    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("");//ip address
    ex.sin_family = AF_INET;//Address family
    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);//Tell program to wait for connections

        if(Connect = accept(Listen, (SOCKADDR*)&ex, (int*)&length))
            std::cout<<"\nConnection accepted!\n";
    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.

Now follow this .gif to test.
[Image: Telnet.gif]
(This post was last modified: 02-16-2011 01:49 AM by Scorch.)
01-31-2011 06:24 AM
Find all posts by this user Quote this message in a reply
Post Reply 

Forum Jump:

User(s) browsing this thread: