Back to index

avfs  1.0.1
socket.c
Go to the documentation of this file.
00001 /*
00002     AVFS: A Virtual File System Library
00003     Copyright (C) 2000-2001  Miklos Szeredi <miklos@szeredi.hu>
00004 
00005     This program can be distributed under the terms of the GNU GPL.
00006     See the file COPYING.
00007 */
00008 
00009 #include "socket.h"
00010 #include "avfs.h"
00011 
00012 #include <stdlib.h>
00013 #include <unistd.h>
00014 #include <sys/socket.h>
00015 #include <netdb.h>
00016 #include <netinet/in.h>
00017 
00018 
00019 static int sock_connect_host(const char *hostname, int port)
00020 {
00021     struct hostent *host;
00022     struct sockaddr_in sn;
00023     int sock;
00024     int res;
00025 
00026     host = gethostbyname(hostname);
00027     if(host == NULL) {
00028         av_log(AVLOG_ERROR, "Could not resolve host %s", hostname);
00029         return -ENOENT;
00030     }
00031     
00032     if(host->h_addrtype != AF_INET) {
00033         av_log(AVLOG_ERROR, "Cannot handle non-inet address %s", hostname);
00034         return -ENOENT;
00035     }
00036 
00037     sn.sin_family = AF_INET;
00038     sn.sin_port = htons(port);
00039     memcpy(&sn.sin_addr, host->h_addr_list[0], host->h_length);
00040 
00041     sock = socket(AF_INET, SOCK_STREAM, 0);
00042     if(sock == -1) {
00043         av_log(AVLOG_ERROR, "socket(): %s", strerror(errno));
00044         return -errno;
00045     }
00046 
00047     res = connect(sock, (struct sockaddr *) &sn, sizeof(sn));
00048     if(res == -1) {
00049         av_log(AVLOG_ERROR, "connect(): %s", strerror(errno));
00050         close(sock);
00051         return -errno;
00052     }
00053 
00054     return sock;
00055 }
00056 
00057 int av_sock_connect(const char *name, int defaultport)
00058 {
00059     char *hostname;
00060     char *s;
00061     int port = defaultport;
00062     int sock;
00063 
00064     hostname = av_strdup(name);
00065     s = strrchr(hostname, ':');
00066     if(s != NULL) {
00067         char *end;
00068 
00069         *s = '\0';
00070         s++;
00071         port = strtol(s, &end, 10);
00072         if(end == s || *end != '\0') {
00073             av_free(hostname);
00074             av_log(AVLOG_ERROR, "Bad port: %s", name);
00075             return -ENOENT;
00076         }
00077     }
00078     else if(defaultport == -1) {
00079         av_free(hostname);
00080         av_log(AVLOG_ERROR, "Missing port: %s", name);
00081         return -ENOENT;
00082     }
00083     
00084     sock = sock_connect_host(hostname, port);
00085     av_free(hostname);
00086     
00087     return sock;
00088 }