Socket Programming


 
Thread Tools Search this Thread
Operating Systems Linux Ubuntu Socket Programming
# 1  
Old 08-03-2011
Question Socket Programming

HI
Can anyone provide me with codes for file transfer server to client or vice versa?
Also please explain how to compile those programs in ubuntu terminal as i am totally new to socket programming.

Thanks
# 2  
Old 08-03-2011
Client is one code, Server is another.

You use C, traditionally, but now sockets are available in all languages. An example tcp/ip server I wrote is around here somewhere, u_inetd.c: Is this case is normal when programming in socket? It just listens and executes the server instance, so the server needs no sockets code unless you want to rewrite something ugly like FTP itself. This is like UNIX inetd, but for high ports, one app each and no root needed! If you find code for tcp_relay.c, it is a tcp server that for every connection fires up a client and shuffles the data back and forth, so all tcp code is in there. Sockets can do udp, too, and other protocols peer to tcp and udp, by raw IP packet sockets.

There are many tutorials on each language, sockets in it, and ubuntu can run them all.

Now, are you writing your own file transfer protocol, and why?

Here is tcp_relay.c as I last used it:
Code:
$ cat mysrc/tcp_relay.c
/* This software is Copyright 1995, 1996 by Karl-Johan Johnsson
 * Modified by Voon-Li Chung to allow access from any host
 *
 * Permission is hereby granted to copy, reproduce, redistribute or otherwise
 * use this software as long as: there is no monetary profit gained
 * specifically from the use or reproduction of this software, it is not
 * sold, rented, traded or otherwise marketed, and this copyright notice is
 * included prominently in any copy made. 
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ANY USE OF THIS
 * SOFTWARE IS AT THE USER'S OWN RISK.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/wait.h>
#undef  False
#define False 0
#undef  True
#define True  1
#define DEFAULT_REMOTE_PORT     119
/*
 *  Define this if <unistd.h> doesn't declare getopt() and friends.
 */
#define BOGUS_UNISTD
static void perror_exit(const char *msg)
{
    perror(msg);
    _exit(1);
}
static void* xrealloc(void *ptr, size_t size)
{
    if (!ptr)
        ptr = malloc(size); /* Hack for broken C libraries */
    else
        ptr = realloc(ptr, size);
    if (!ptr)
        perror_exit("malloc");
    return ptr;
}
static struct sockaddr_in get_remote_host(char *host)
{
    struct sockaddr_in  addr;
    struct hostent      *hent;
    char                *c;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = PF_INET;
    addr.sin_port   = htons(DEFAULT_REMOTE_PORT);
    c = strchr(host, ':');
    if (c) {
        *c++ = '\0';
        /* FIXME: error check? */
        addr.sin_port = htons(atoi(c));
    }
    hent = gethostbyname(host);
    if (!hent) {
        fprintf(stderr, "No such host: %s\n", host);
        _exit(1);
    }
    memcpy(&addr.sin_addr, hent->h_addr, hent->h_length);
    return addr;
}
static int do_rw(int from, int to)
{
    static char buffer[16384];
    char        *c;
    long        i, j, n;
    do {
        n = read(from, buffer, sizeof buffer);
    } while (n < 0 && errno == EINTR);
    c = buffer;
    i = n;
    while (i > 0) {
        j = write(to, c, i);
        if (j < 0)
            if (errno == EINTR)
                continue;
            else
                return -1;
        if (j == 0)
            return 0;
        c += j;
        i -= j;
    }
    return n;
}
static int open_serv_socket(struct sockaddr_in *serv_addr)
{
    int ss, tmp;
    ss = socket(PF_INET, SOCK_STREAM, 0);
    if (ss < 0)
        return -1;
    do {
        tmp = connect(ss, (struct sockaddr *)serv_addr, sizeof *serv_addr);
    } while (tmp < 0 && errno == EINTR);
    if (tmp < 0) {
        perror("connect");
        close(ss);
        return -1;
    }
    return ss;
}
static int child(struct sockaddr_in *serv_addr, int cs)
{
    fd_set      fds;
    int         max, ss, tmp = 0;
    ss = open_serv_socket(serv_addr);
    if (ss < 0)
        return -1;
    FD_ZERO(&fds);
    FD_SET(cs, &fds);
    FD_SET(ss, &fds);
    max = (cs > ss ? cs : ss) + 1;
    for (;;) {
        fd_set  rd_fds = fds;
        tmp = select(max, &rd_fds, NULL, NULL, NULL);
        if (tmp < 0)
            if (errno == EINTR)
                continue;
            else
                break;
        if (FD_ISSET(cs, &rd_fds)) {
            tmp = do_rw(cs, ss);
            if (tmp <= 0)
                break;
        }
        if (FD_ISSET(ss, &rd_fds)) {
            tmp = do_rw(ss, cs);
            if (tmp <= 0)
                break;
        }
    }
    if (tmp < 0)
        perror("read/write");
    close(ss);
    return tmp;
}
static void doit(struct sockaddr_in *serv_addr, int port, int single)
{
    struct sockaddr_in  local_addr, cli_addr;
    int                 as;
    int                 yes = 1;
    memset(&local_addr, 0, sizeof local_addr);
    local_addr.sin_family = PF_INET;
    local_addr.sin_port = port;
    as = socket(PF_INET, SOCK_STREAM, 0);
    if (as < 0)
        perror_exit("socket");
    if (setsockopt(as, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof yes) < 0)
        perror_exit("setsockopt(SO_REUSEADDR)");
    if (bind(as, (struct sockaddr *)&local_addr, sizeof local_addr) < 0)
        perror_exit("bind");
    if (listen(as, 5) < 0)
        perror_exit("listen");
    for (;;) {
        int     cs, len;
        do {
            len = sizeof cli_addr;
            cs = accept(as, (struct sockaddr *)&cli_addr, &len);
        } while (cs < 0 && errno == EINTR);
        if (cs < 0)
            perror_exit("accept");
        if (single)
            child(serv_addr, cs);
        else
            switch (fork()) {
            case -1:
                perror_exit("fork");
                break;
            case 0:
                if (child(serv_addr, cs) < 0)
                    _exit(1);
            default:
                break;
            }
        close(cs);
    }
}
/************************************************************************/
static void sig_chld(int no)
{
    while (waitpid(-1, NULL, WNOHANG) > 0);
}
static void install_sig_handlers(void)
{
    struct sigaction    sig_act;
    sig_act.sa_handler = sig_chld;
    sig_act.sa_flags   = 0;
    sigfillset(&sig_act.sa_mask);
    if (sigaction(SIGCHLD, &sig_act, NULL) < 0)
        perror_exit("sigaction(SIGCHLD)");
    sig_act.sa_handler = SIG_IGN;
    sig_act.sa_flags = 0;
    sigemptyset(&sig_act.sa_mask);
    if (sigaction(SIGPIPE, &sig_act, NULL) < 0)
        perror_exit("sigaction(SIGPIPE)");
}
static void usage(char *name)
{
    fprintf(stderr, "Usage: %s -p port [-s] remotehost:port\n",
            name);
    _exit(1);
}
int main(int argc, char *argv[])
{
    struct sockaddr_in  serv_addr;
    int                 single = False;
    int                 port = 0;
    int                 c;
#ifdef BOGUS_UNISTD
    extern int   getopt(int, char *const[], const char*);
    extern char *optarg;
    extern int   optind, opterr;
#endif
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    install_sig_handlers();
    opterr = 0;
    while ((c = getopt(argc, argv, "p:h:s")) != -1)
        switch (c) {
        case 'p': /* port to listen on */
            if (sscanf(optarg, "%d", &port) != 1 || port < 0)
                usage(argv[0]);
            port = htons(port);
            break;
        case 's':
            single = True;
            break;
        default:
            usage(argv[0]);
            break;
        }
    if (optind != argc - 1 || port == 0)
        usage(argv[0]);
    serv_addr = get_remote_host(argv[optind]);
    doit(&serv_addr, port, single);
    return 0;
}

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

socket programming

how to include socket.h in visual studio 2005.. (2 Replies)
Discussion started by: asd123
2 Replies

2. Programming

Socket programming

Hi everyone, I'm new to this forum. I'm working on new project for last few days and this forum already helped me on couple of occasions. I don't have any prior experience with network programming so I'll appreciate any advise given. I'm trying to do the following: 1. open user... (2 Replies)
Discussion started by: _thomas
2 Replies

3. UNIX for Dummies Questions & Answers

hi i need help with socket programming

in socket programming how can i : Create for example 3 blank files, namely: server, client, network •Server: act as servers/provider, will receive all requests from different client •Client: requesters •Network: middle-layer of communication between server & client any tips or... (6 Replies)
Discussion started by: kedah160
6 Replies

4. UNIX for Advanced & Expert Users

socket programming

can we send udp message to a destination ip address .. without having an ip address configured in our machine using recvfrom ? (2 Replies)
Discussion started by: Gopi Krishna P
2 Replies

5. Programming

help regarding socket programming

i m using sockets for setting up a connection between a server and a client. When the clients gets connected to the server, its ip is conveyed to the server through one of the predefined structures in c library... i save this ip address in an array....1st client's ip address goes to the zeroth... (1 Reply)
Discussion started by: abmxla007
1 Replies

6. IP Networking

socket programming

Hello Everyone Iam working on tcp/ip programming.with some time interval server has to send data.client has to close the connection and to open the connection between the time interval.this is the scenario when iam closing the connection in client side the connection terminates.how to... (1 Reply)
Discussion started by: sureshvaikuntam
1 Replies

7. IP Networking

socket programming

my system is a stand alone system... i want to try doing socket porgramming..ihave heard that this is usually done during testing... how can i do that....? (6 Replies)
Discussion started by: damn_bkb
6 Replies

8. Programming

Need Help Regarding Socket Programming

Can anyone plz me. I need a sample code for the following description. Its urgent. It is C/Socket program with the following descriptions: NAME coreadServer - Concurrent Readers Server. coreadClient - Concurrent Readers Client. SYNOPSIS coreadServer <OutputFile> coreadClient <n>... (1 Reply)
Discussion started by: priya.vmr
1 Replies

9. Programming

Socket Programming socket

Hello, I actually try to make client-server program. I'm using SCO OpenServer Release 5.0.0 and when I try to compile my code (by TELNET) I've got this error : I'm just using this simple code : and I get the same error if I use : If someone can help me, Thanks (2 Replies)
Discussion started by: soshell
2 Replies

10. Programming

Socket Programming

Dear Reader, Is there any way to check up socket status other than 'netstatus ' Thanks in advance, (1 Reply)
Discussion started by: joseph_shibu
1 Replies
Login or Register to Ask a Question