• RSS
  • Twitter
  • FaceBook

Security Forums

Log in

FAQ | Search | Usergroups | Profile | Register | RSS | Posting Guidelines | Recent Posts

[C] socket newbie

Users browsing this topic:0 Security Fans, 0 Stealth Security Fans
Registered Security Fans: None
Post new topic   Reply to topic   Printer-friendly version    Networking/Security Forums Index -> Programming and More

View previous topic :: View next topic  
Author Message
billiejoex
Just Arrived
Just Arrived


Joined: 22 Nov 2004
Posts: 0


Offline

PostPosted: Fri Jun 24, 2005 12:52 am    Post subject: [C] socket newbie Reply with quote

Hi all.
I got a basical knowledge of C sintax on Windows platforms and I would try to begin learning socket programming to create some simple TCP/IP applications. Here's some question:

1) First of all I'd have need a good resource on wich I could study on.
An "idiot-guide" in wich also the smaller palrticular is explained. Can you suggest me something in particular?

2) I use windows and a linux platforms too. Does what would be better for me? Socket or winsocket? I got the feeling that the first are easier but the bigger spreading of the Windows platforms could help me with a bigger amount of related documentation.

2b) Are the differences between socket and winsock substantial?
Supposing that I begin to learn socket programmin do could I have problems to use winsock, in future?
Moreover, does the platforms difference strongly influences on C programming?

3) How much important is the C knowledge? Does it's foundamental to program very well to programming sockets???
Personally I think to have an insufficient skill yet.
I read at some how toes, I know the basics like variabiles, arrays, structures etc... but the gaps are obvious,

I'm sorry for the quantity of noob questions but I'd really like to begin to create net-related programs.

Thanks to anyone will help me.

PS - really sorry for my bad english.


greetings
Back to top
View user's profile Send private message
E-Mind
Just Arrived
Just Arrived


Joined: 25 May 2005
Posts: 0
Location: Palo Alto, CA

Offline

PostPosted: Fri Jun 24, 2005 1:13 am    Post subject: Reply with quote

Quote:
Getting Started with Winsock

The following is a step-by-step guide to getting started with Windows Sockets programming. It is designed to provide an understanding of basic Winsock functions and data structures, and how they work together.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/getting_started_with_winsock.asp


As for the difference between windows and linux - not much is different and once you get the hang of it - switching around and/or writing portable code (i.e. code that would work on multiple platforms) would become easier.

Complete Client Code:
Code:
#include <stdio.h>
#include "winsock2.h"

void main() {

    // Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
    if ( iResult != NO_ERROR )
        printf("Error at WSAStartup()\n");

    // Create a socket.
    SOCKET m_socket;
    m_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

    if ( m_socket == INVALID_SOCKET ) {
        printf( "Error at socket(): %ld\n", WSAGetLastError() );
        WSACleanup();
        return;
    }

    // Connect to a server.
    sockaddr_in clientService;

    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
    clientService.sin_port = htons( 27015 );

    if ( connect( m_socket, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR) {
        printf( "Failed to connect.\n" );
        WSACleanup();
        return;
    }

    // Send and receive data.
    int bytesSent;
    int bytesRecv = SOCKET_ERROR;
    char sendbuf[32] = "Client: Sending data.";
    char recvbuf[32] = "";

    bytesSent = send( m_socket, sendbuf, strlen(sendbuf), 0 );
    printf( "Bytes Sent: %ld\n", bytesSent );

    while( bytesRecv == SOCKET_ERROR ) {
        bytesRecv = recv( m_socket, recvbuf, 32, 0 );
        if ( bytesRecv == 0 || bytesRecv == WSAECONNRESET ) {
            printf( "Connection Closed.\n");
            break;
        }
        if (bytesRecv < 0)
            return;
        printf( "Bytes Recv: %ld\n", bytesRecv );
    }

    return;
}


Complete Server Code:
Code:
#include <stdio.h>
#include "winsock2.h"

void main() {

    // Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
    if ( iResult != NO_ERROR )
        printf("Error at WSAStartup()\n");

    // Create a socket.
    SOCKET m_socket;
    m_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

    if ( m_socket == INVALID_SOCKET ) {
        printf( "Error at socket(): %ld\n", WSAGetLastError() );
        WSACleanup();
        return;
    }

    // Bind the socket.
    sockaddr_in service;

    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr( "127.0.0.1" );
    service.sin_port = htons( 27015 );

    if ( bind( m_socket, (SOCKADDR*) &service, sizeof(service) ) == SOCKET_ERROR ) {
        printf( "bind() failed.\n" );
        closesocket(m_socket);
        return;
    }
   
    // Listen on the socket.
    if ( listen( m_socket, 1 ) == SOCKET_ERROR )
        printf( "Error listening on socket.\n");

    // Accept connections.
    SOCKET AcceptSocket;

    printf( "Waiting for a client to connect...\n" );
    while (1) {
        AcceptSocket = SOCKET_ERROR;
        while ( AcceptSocket == SOCKET_ERROR ) {
            AcceptSocket = accept( m_socket, NULL, NULL );
        }
        printf( "Client Connected.\n");
        m_socket = AcceptSocket;
        break;
    }
   
    // Send and receive data.
    int bytesSent;
    int bytesRecv = SOCKET_ERROR;
    char sendbuf[32] = "Server: Sending Data.";
    char recvbuf[32] = "";
   
    bytesRecv = recv( m_socket, recvbuf, 32, 0 );
    printf( "Bytes Recv: %ld\n", bytesRecv );
   
    bytesSent = send( m_socket, sendbuf, strlen(sendbuf), 0 );
    printf( "Bytes Sent: %ld\n", bytesSent );

    return;
}


Here is a linux socket client program to compare to:
Code:
/************************************************************************/
/*   PROGRAM NAME: client_ex.c  (works with server_ex.c)                */
/*                                                                      */
/*   client_ex.c DESCRIPTION:                                           */
/*   Client creates a socket to connect to Server.                      */
/*   When the communication established, Client writes data to server   */
/*   and echoes the response from Server.                               */
/*                                                                      */
/*   To run this program, first compile the server_ex.c and run it      */
/*   on a server machine. Then run the client program on another        */
/*   machine.                                                           */
/*                                                                      */
/*   SOLARIS:    gcc -o client_ex client_ex.c -lsocket -lnsl            */
/*   LINUX:      gcc -o client_ex client_ex.c -lnsl                     */
/*   client_ex server_name                                              */
/*                                                                      */
/************************************************************************/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>  /* define socket */
#include <netinet/in.h>  /* define internet socket */
#include <netdb.h>       /* define internet socket */

#define SERVER_PORT 9999     /* define a server port number */

int main( int argc, char* argv[] )
{
    int sd;
    struct sockaddr_in server_addr = { AF_INET, htons( SERVER_PORT ) };
    char buf[512];
    struct hostent *hp;

    if( argc != 2 )
    {
   printf( "Usage: %s hostname\n", argv[0] );
   exit( 1 );
    }

    /* get the host */
    if( ( hp = gethostbyname( argv[1] ) ) == NULL )
    {
   printf( "%s: %s unknown host\n", argv[0], argv[1] );
   exit( 1 );
    }
    bcopy( hp->h_addr_list[0], (char*)&server_addr.sin_addr, hp->h_length );

    /* create a socket */
    if( ( sd = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 )
    {
   perror( "client: socket failed" );
   exit( 1 );
    }

    /* connect a socket */
    if( connect( sd, (struct sockaddr*)&server_addr,
       sizeof(server_addr) ) == -1 )
    {
   perror( "client: connect failed" );
   exit( 1 );
    }

    printf("connect() successful! will send a message to server\n");
    printf("Input a string:\n" );

    while( scanf( "%s", buf) != EOF)
    {
     write(sd, buf, sizeof(buf));
      read(sd, buf, sizeof(buf));
      printf("SERVER ECHOED: %s\n", buf);
    }

    close(sd);
    return(0);
}
http://web.umr.edu/~ercal/284/client_ex.c

As for the "particulars" - take this advice - go through each statement and read the documentation on the specific function either on MSDN or use google to search (using the function name as the keyword) - to find out what the return values are and what the function arguments needs to be. With practice, you would get the hang of it, and hopefully be able to do this research on your own. Wink


Good Luck,
E-Mind
Back to top
View user's profile Send private message
billiejoex
Just Arrived
Just Arrived


Joined: 22 Nov 2004
Posts: 0


Offline

PostPosted: Tue Jun 28, 2005 2:41 am    Post subject: Reply with quote

Thanx for the sources.
Back to top
View user's profile Send private message
Display posts from previous:   

Post new topic   Reply to topic   Printer-friendly version    Networking/Security Forums Index -> Programming and More All times are GMT + 2 Hours
Page 1 of 1


 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

Community Area

Log in | Register