コード例 #1
0
ファイル: main.c プロジェクト: cristianbercaru/linphone_proxy
static inline void migrate_redirect()
{
	printf("redirecting to ip: %s\n", redirect_ip);

	remote_ip = redirect_ip;
	init_sockaddr(&proxy_to_proxy_addr, remote_ip, SIP_PROXY);
	init_sockaddr(&proxy_to_proxy_data_addr, remote_ip, DATA_PROXY);
}
コード例 #2
0
ファイル: main.c プロジェクト: cristianbercaru/linphone_proxy
static inline void migrate_init()
{
	char buffer[MAX_PACKET_SIZE];
	struct timeval t1, t2, dt;

	gettimeofday_safe(&t1);
	eprintf("migrate to IP: #%s#\n", migrate_ip);
	init_sockaddr(&migrate_addr, migrate_ip, MANAGER_PORT);

	strcpy(buffer, "establish");
	send_msg(manager_socket, &migrate_addr, buffer, strlen(buffer));
	printf("sent establish\n");

	send_msg(manager_socket, &migrate_addr, out_invite.buffer, out_invite.size);
	printf("sent INIT\n");

	send_msg(manager_socket, &migrate_addr, out_ack.buffer, out_ack.size);
	printf("sent ACK\n");

	send_msg(manager_socket, &migrate_addr, out_op_ok.buffer, out_op_ok.size);
	printf("sent OPTIONS OK\n");

	recv_msg(manager_socket, &migrate_addr, buffer);
	printf("\nreceived:\n%s\n", buffer);
	gettimeofday_safe(&t2);

	time_diff(&t1, &t2, &dt);
	printf("time 1: %lu.%06lu\n", dt.tv_sec, dt.tv_usec);

	init_sockaddr(&migrate_addr, remote_ip, MANAGER_PORT);
	strcpy(buffer, "redirect: ");
	strcat(buffer, migrate_ip);
	gettimeofday_safe(&t1);
	send_msg(manager_socket, &migrate_addr, buffer, strlen(buffer));
	gettimeofday_safe(&t2);

	time_diff(&t1, &t2, &dt);
	printf("time 2: %lu.%06lu\n", dt.tv_sec, dt.tv_usec);

	gettimeofday_safe(&t1);
	get_data(out_ack.buffer, &ack_data);
	memset(buffer, 0, MAX_PACKET_SIZE);
	strcpy(buffer, bye);
	replace_all(buffer, "local_ip", local_ip);
	replace_all(buffer, "remote_ip", remote_ip);
	replace_all(buffer, "from_tag", ack_data.to_tag);
	replace_all(buffer, "to_tag", ack_data.from_tag);
	replace_all(buffer, "call_id", ack_data.call_id);
	send_msg(proxy_to_linphone_socket, &proxy_to_linphone_addr, buffer, strlen(buffer));
	gettimeofday_safe(&t2);

	time_diff(&t1, &t2, &dt);
	printf("time 3: %lu.%06lu\n", dt.tv_sec, dt.tv_usec);
}
コード例 #3
0
ファイル: authcli.c プロジェクト: BackupGGCode/wl500g
static void request_auth_child(void)
{
    int sock;
    int ret;
    struct sockaddr_in serveraddr;

    sock = socket (PF_INET, SOCK_STREAM, 0);
    if ((sock > 0) && init_sockaddr(&serveraddr, HOSTNAME, SERV_TCP_PORT)) {
	log_dbg("connecting to auth server at %s", inet_ntoa(serveraddr.sin_addr));

	while(1) {
	    ret = connect(sock, (struct sockaddr*) &serveraddr, sizeof(serveraddr));
	    if (ret == ENETUNREACH) {
		log_dbg("network unreachable - reconnecting");
		sleep(RECONNECT_DELAY);
	    } else
	       break;
	}

	if (!ret) {
	    log_dbg("sending init request");
	    send(sock, "IMAL", 4, 0);
	} else
	    log_dbg("connect error: %s", strerror(errno));
	close(sock);
    }
}
コード例 #4
0
ファイル: ftp_proxy.cpp プロジェクト: kthxbyte/KDE1-Linaro
KProtocolProxyFTP::KProtocolProxyFTP () {

    use_proxy = 0;
    int port = 80;

    QString proxyStr;
    QString tmp;
    KURL proxyURL;
    
    // All right. Now read the proxy settings
    // KSimpleConfig prxcnf(KApplication::localconfigdir() + "/kfmrc");
    // Read Only
    KSimpleConfig prxcnf(KApplication::localconfigdir() + "/kfmrc", true );
    prxcnf.setGroup("Browser Settings/Proxy");

    noProxyForStr = prxcnf.readEntry("NoProxyFor");
    
    tmp = prxcnf.readEntry( "UseProxy" );
    if ( tmp == "Yes" ) { // Do we need proxy?
        proxyStr = prxcnf.readEntry( "FTP-Proxy" );
        proxyURL = proxyStr.data();
        // printf( "Using ftp proxy %s on port %d\n", proxyURL.host(), proxyURL.port() );
        port = proxyURL.port();
	if ( port == 0 )
	    port = 80;

	proxy_user = prxcnf.readEntry( "Proxy-User" );
	proxy_pass = prxcnf.readEntry( "Proxy-Pass" );

	init_sockaddr(&proxy_name, proxyURL.host(), port);
	use_proxy = 1;
    }
}
コード例 #5
0
ファイル: srpc_network.c プロジェクト: xysmas/rpc
void init_netinfo(Srpc_net_info *ni, const char *hostname, uint16_t port)
{
  printf("initializing custom netinfo struct\n");
  ni->socket_no = init_sockaddr(&ni->si_other, hostname, port);
  /* ni->socketfd = make_socket(port); */

}
コード例 #6
0
ファイル: inetcli.c プロジェクト: cmjonze/eglibc_svn
int
main (void)
{
    extern void init_sockaddr (struct sockaddr_in *name,
                               const char *hostname,
                               uint16_t port);
    int sock;
    struct sockaddr_in servername;

    /* Create the socket.  */
    sock = socket (PF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        perror ("socket (client)");
        exit (EXIT_FAILURE);
    }

    /* Connect to the server.  */
    init_sockaddr (&servername, SERVERHOST, PORT);
    if (0 > connect (sock,
                     (struct sockaddr *) &servername,
                     sizeof (servername)))
    {
        perror ("connect (client)");
        exit (EXIT_FAILURE);
    }

    /* Send data to the server.  */
    write_to_server (sock);
    close (sock);
    exit (EXIT_SUCCESS);
}
コード例 #7
0
ファイル: device.c プロジェクト: hwjjacky/yee_link_light
char * create_device(struct device *dev){
	char *cmd;
	struct hostent *host=NULL;
	int sockfd;
	struct sockaddr_in sockaddr;
	host=gethost();
	if(NULL==host){
		return NULL;
	}
	sockfd=getsocket();
	if(-1==sockfd){
		return NULL;
	}
	init_sockaddr(&sockaddr,host);
	if(-1==(getconnect(sockfd,&sockaddr))){
		return NULL;
	}
	cmd=link_deviceinfo("/v1.0/devices",dev);
	if(-1==(sencmd(sockfd,cmd))){
		return NULL;
	}
	if(NULL==(cmd=receivecmd(sockfd))){
		return NULL;
	}
	closesocket(sockfd);
	return cmd;
}
コード例 #8
0
jint sendTo0(JNIEnv * env, jint fd, void* buffer, jint pos, jint limit ,jbyteArray address, jint scopeId, jint port) {
    struct sockaddr_storage addr;
    init_sockaddr(env, address, scopeId, port, &addr);

    ssize_t res;
    int err;
    do {
       res = sendto(fd, buffer + pos, (size_t) (limit - pos), 0, (struct sockaddr *)&addr, sizeof(struct sockaddr_storage));
       // keep on writing if it was interrupted
    } while(res == -1 && ((err = errno) == EINTR));

    if (res < 0) {
        // network stack saturated... try again later
        if (err == EAGAIN || err == EWOULDBLOCK) {
            return 0;
        }
        if (err == EBADF) {
            throwClosedChannelException(env);
            return -1;
        }
        throwIOException(env, exceptionMessage("Error while sendto(...): ", err));
        return -1;
    }
    return (jint) res;
}
コード例 #9
0
ファイル: car.c プロジェクト: engie/spycar
int main (int argc, char** argv)
{
    int sock;
    struct sockaddr_in servername;
    
    cvInitSystem( argc, argv );
    cvNamedWindow ("Source", CV_WINDOW_AUTOSIZE);

    koki = koki_new();

    /* Create the socket. */
    sock = socket (PF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        perror ("socket (client)");
        exit (EXIT_FAILURE);
    }

    /* Connect to the server. */
    init_sockaddr (&servername, SERVERHOST, PORT);
    if (0 > connect (sock,
                (struct sockaddr *) &servername,
                sizeof (servername)))
    {
        perror ("connect (client)");
        exit (EXIT_FAILURE);
    }
    
    stream_images( sock );
    close (sock);
    exit (EXIT_SUCCESS);
}
コード例 #10
0
int CommSocketClient::open_socket(const char *hostname, unsigned int port, bool global)
{
    int sock;
    sockaddr_in gaddr;
    sockaddr_un laddr;
    sockaddr *addr=(sockaddr *)&gaddr;
    int n=sizeof(sockaddr_in);
    int set=1;
    
    sock=socket(global ? PF_INET : PF_LOCAL, SOCK_STREAM, 0);
    if(sock<0)
        return -1;
    if(!global)
    {
        laddr.sun_family=AF_LOCAL;
        sprintf(laddr.sun_path, "%d", port);
        addr=(sockaddr *) &laddr;
        n=SUN_LEN(&laddr);
    }
    else if(!init_sockaddr(&gaddr, "localhost", port))
    {
        close(sock);
        return -1;
    }
    if(connect(sock, addr, n)<0)
    {
        close(sock);
        cerr << "connect failed" << endl;
        return -1;
    }
    return sock;
}
コード例 #11
0
ファイル: remotejoy.c プロジェクト: yin8086/psplinkusb
int connect_to(const char *ipaddr, unsigned short port)
{
	struct sockaddr_in name;
	int sock = -1;
	int flag = 1;

	sock = socket(PF_INET, SOCK_STREAM, 0);

	if(sock < 0)
	{
		perror("socket");
		return -1;
	}

	if(!init_sockaddr(&name, ipaddr, port))
	{
		printf("Could not initialise socket address\n");
		close(sock);
		return -1;
	}

	if(connect(sock, (struct sockaddr *) &name, sizeof(name)) < 0)
	{
		perror("connect");
		close(sock);
		return -1;
	}

	/* Disable NAGLE's algorithm to prevent the packets being joined */
	setsockopt(sock, SOL_TCP, TCP_NODELAY, &flag, sizeof(int));

	return sock;
}
コード例 #12
0
ファイル: myclient.c プロジェクト: eburdon/OpenSSL-Practice
/* Open standard TCP socket
 * Shamelessly stolen from Assignment 2's oldClient.c*/
int open_socket(char *hostname, int port)
{
  /* Client Information */
  int sock;
  struct sockaddr_in servername;

  fprintf(stderr, "Opening connection to [%s][%d]\n", hostname, port);

  /* Create the TCP socket */
  sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sock < 0) {
    perror ("socket (client)");
    exit (EXIT_FAILURE);
  }

  /* Connect to the server.   */
  init_sockaddr (&servername, hostname, port);
  if (connect (sock,
              (struct sockaddr *) &servername,
               sizeof (servername)) != 0) 
  {
    /* If connection fails, notify user... */
    perror ("connect (client)");
    exit (EXIT_FAILURE);
  }

  fprintf(stderr, "Connected to socket descriptor %d\n",sock);
  return sock;
}
コード例 #13
0
ファイル: device.c プロジェクト: hwjjacky/yee_link_light
char * edit_device(int devid,struct device *dev){
	char device_id[30];
	char tmp_str[50];
	char *cmd;
	struct hostent *host=NULL;
	int sockfd;
	struct sockaddr_in sockaddr;
	host=gethost();
	if(NULL==host){
		return NULL;
	}
	sockfd=getsocket();
	if(-1==sockfd){
		return NULL;
	}
	init_sockaddr(&sockaddr,host);
	if(-1==(getconnect(sockfd,&sockaddr))){
		return NULL;
	}
	sprintf(device_id,"%d",devid);
	memset(tmp_str,0,sizeof(tmp_str));
	strcat(tmp_str,"/v1.0/device/");
	strcat(tmp_str,device_id);
	cmd=link_deviceinfo(tmp_str,dev);
	if(-1==(sencmd(sockfd,cmd))){
		return NULL;
	}
	if(NULL==(cmd=receivecmd(sockfd))){
		return NULL;
	}
	closesocket(sockfd);
	return cmd;
}
コード例 #14
0
ファイル: device.c プロジェクト: hwjjacky/yee_link_light
char *show_device(int devid){
	char cmd[MAXBUFF];
	char device_id[30];
	char *ret;
	struct hostent *host=NULL;
	int sockfd;
	struct sockaddr_in sockaddr;
	host=gethost();
	if(NULL==host){
		return NULL;
	}
	sockfd=getsocket();
	if(-1==sockfd){
		return NULL;
	}
	init_sockaddr(&sockaddr,host);
	if(-1==(getconnect(sockfd,&sockaddr))){
		return NULL;
	}
	sprintf(device_id,"%d",devid);
	memset(cmd,0,sizeof(cmd));
	strcat(cmd,"GET /v1.0/device/");
	strcat(cmd,device_id);
	strcat(cmd," HTTP/1.1\r\nHost: api.yeelink.net\r\nU-ApiKey: ");
	strcat(cmd,yeelink_apikey);
	strcat(cmd,"\r\n\r\n");
	if(-1==(sencmd(sockfd,cmd))){
		return NULL;
	}
	if(NULL==(ret=receivecmd(sockfd))){
		return NULL;
	}
	closesocket(sockfd);
	return ret;
}
コード例 #15
0
JNIEXPORT void JNICALL Java_io_netty_channel_epoll_Native_bind(JNIEnv * env, jclass clazz, jint fd, jbyteArray address, jint scopeId, jint port) {
    struct sockaddr_storage addr;
    init_sockaddr(env, address, scopeId, port, &addr);

    if(bind(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1){
        int err = errno;
        throwIOException(env, exceptionMessage("Error during bind(...): ", err));
    }
}
コード例 #16
0
ファイル: serverC.c プロジェクト: YeulChang/distributed-atm
int make_socket(int type,unsigned int server)
{
	int sock;
	struct sockaddr_in name;
	if((sock=socket(AF_INET,type,0))<0)
		printf("socket error\n");
	name=init_sockaddr(server);
	if(bind(sock,(struct sockaddr *)&name,(socklen_t)sizeof(name))<0)
		printf("bind\n");
	return sock;
}
コード例 #17
0
ファイル: client_vsock.c プロジェクト: tudor1805/lvkd
int main() 
{
	int afVMCI;
	int sockfd;
	int num_bytes;
	char buffer[BUFFSIZE];
	long bytes_sent = 0;
	uint64_t buf_size;
	socklen_t len;
	struct sockaddr_vm server_addr = {0};

	/*Obtain VMCI address family*/
	afVMCI = VMCISock_GetAFValue();
	init_sockaddr(afVMCI, &server_addr);

	strcpy(buffer, "== Hello Server ==");

	printf("Creating socket...\n");	

	/*Create a VMCI socket*/
	if ((sockfd = socket(afVMCI, SOCK_STREAM, 0)) == -1) 
		error("socket");

	printf("Connecting to server...\n");

	if ((connect(sockfd, (struct sockaddr *) &server_addr, sizeof server_addr)) == -1) 
		error("connect");	

	if (getsockopt(sockfd, afVMCI, SO_VMCI_BUFFER_SIZE, (void *)&buf_size, &len) == -1) 
		error("getsockopt");

	printf("Current buffer : %lld\n", buf_size);
	getchar();
		
	printf("Sending data...\n");
	while(1) {
		if ((num_bytes = send(sockfd, buffer, BUFFSIZE, 0)) == -1) 
			break;	
		bytes_sent += num_bytes;
		printf("Sent %ld\n", bytes_sent);
	}
	
	printf("Sent %ld\n", bytes_sent);
	printf("Closing app...\n");	
	close(sockfd);

	return 0;
}
コード例 #18
0
void setup ()
{
     int sockfd;
     struct sockaddr_in serv_addr;
     stop_running=0;

     //set the sigpipe handler so we don't exit upon a sigpipe
     //this happens when we complete the course in tracksail and the tcp connection to it goes dead
     signal (SIGPIPE, catch_sigpipe);

     sockfd = socket(AF_INET, SOCK_STREAM, 0);

     if (sockfd < 0)
     {
        perror("ERROR opening socket");
     }


     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = inet_addr(SERVER);
     serv_addr.sin_port = htons(PORT);

     // extern void init_sockaddr (struct sockaddr_in *name, const char *hostname, uint16_t port);

    struct sockaddr_in servername;

    /* Create the socket. */
    sock = socket (PF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        perror ("socket (client)");
        exit (EXIT_FAILURE);
    }

    /* Connect to the server. */
    init_sockaddr (&servername, SERVER, PORT);
    if (0 > connect (sock, (struct sockaddr *) &servername,sizeof (servername)))
    {
        perror ("connect (client)");
        exit (EXIT_FAILURE);
    }

    isSetup=TRUE;
}
コード例 #19
0
ファイル: ethtest_standalone.c プロジェクト: lianqiw/maos
/*
  Connect to a host at port.
  mode=0: read/write
  mode=1: read only by the client. the server won't read
  mode=2: write only by the client. the server won't write
*/
int connect_port(const char *hostname, int port, int block, int mode){
    int sock;
    int count=0;
    struct sockaddr_in servername;
    do{
	/* Create the socket. */
	sock = socket (PF_INET, SOCK_STREAM, 0);
	if (sock < 0) {
	    perror ("socket (scheduler)");
	    return sock;
	}
	{
	    /*Applications that require lower latency on every packet sent should be
	      run on sockets with TCP_NODELAY enabled. It can be enabled through the
	      setsockopt command with the sockets API.  

	      For this to be used effectively, applications must avoid doing small,
	      logically related buffer writes. Because TCP_NODELAY is enabled, these
	      small writes will make TCP send these multiple buffers as individual
	      packets, which can result in poor overall performance.  */
	    int one=1;
	    //setsockopt(sock_mvm, SOL_TCP, TCP_NODELAY|TCP_QUICKACK|TCP_CORK, &one, sizeof(one));
	    setsockopt(sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one));
	}
	/* Give the socket a name. */
	init_sockaddr(&servername, hostname, port);
	if(!block){
	    fcntl(sock, F_SETFD, O_NONBLOCK);
	}
	if(connect(sock, (struct sockaddr *)&servername, sizeof (servername))<0){
	    perror("connect");
	    close(sock);
	    if(!block){
		return -1;
	    }
	    sleep(4);
	    count++;
	}else{
	    return sock;
	}
    }while(count<10);
    return -1; 

}
コード例 #20
0
ファイル: rrd_helpers.c プロジェクト: dmangot/monitor-core
static int
push_data_to_carbon( char *graphite_msg)
{
  int port;
  int sock;
  struct sockaddr_in server;
  int nbytes;

  port = gmetad_config.carbon_port ? gmetad_config.carbon_port : 2003;

  debug_msg("Carbon Proxy:: sending \'%s\' to %s", graphite_msg, gmetad_config.carbon_server);

  /* Create a socket. */
  sock = socket (PF_INET, SOCK_STREAM, 0);
  if (sock < 0)
    {
      perror ("socket (client)");
      close (sock);
      return EXIT_FAILURE;
    }

  /* Connect to the server. */
  init_sockaddr (&server, gmetad_config.carbon_server, port);
  if (0 > connect (sock,
                   (struct sockaddr *) &server,
                   sizeof (server)))
    {
      perror ("connect (client)");
      close (sock);
      return EXIT_FAILURE;
    }

  /* Send data to the server. */
  nbytes = write (sock, graphite_msg, strlen(graphite_msg) + 1);
  if (nbytes < 0)
    {
      perror ("write");
      close (sock);
      return EXIT_FAILURE;
    }

  close (sock);
  return EXIT_SUCCESS;
}
コード例 #21
0
ファイル: pspsh.C プロジェクト: FTPiano/psplinkusb
int connect_to(const char *ipaddr, unsigned short port)
{
	int sock = -1;
	int success = 0;
	struct sockaddr_in name;

	do
	{
		if(!init_sockaddr(&name, ipaddr, port))
		{
			break;
		}
		sock = socket(PF_INET, SOCK_STREAM, 0);
		if(sock < 0)
		{
			perror("socket");
			break;
		}

		if(connect(sock, (struct sockaddr *) &name, sizeof(name)) < 0)
		{
			perror("connect");
			break;
		}
		else
		{
			FD_SET(sock, &g_context.readsave);
		}

		success = 1;
	}
	while(0);

	if(!success)
	{
		if(sock >= 0)
		{
			close(sock);
			sock = -1;
		}
	}

	return sock;
}
コード例 #22
0
ファイル: inet_sock.hpp プロジェクト: hundeboll/netmix
    void sock_bind(int socktype = 0)
    {
        struct addrinfo *res, *rp, hints = {0};
        int err, reuse = 1;

        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = socktype;
        hints.ai_flags = AI_PASSIVE;

        std::cout << m_local_address << std::endl;
        err = getaddrinfo(m_local_address, m_port, &hints, &res);
        if (err)
            throw std::runtime_error(std::string("unable to lookup local address: ") +
                                     gai_strerror(err));

        for (rp = res; rp != NULL; rp = rp->ai_next) {
            m_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if (m_fd < 0)
                continue;

            if (setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)))
                throw std::system_error(errno, std::system_category(),
                                        "unable to set reuse on socket");

            if (bind(m_fd, rp->ai_addr, rp->ai_addrlen) == 0)
                break;

            close(m_fd);
        }

        if (rp == NULL)
            throw std::system_error(errno, std::system_category(),
                                    "unable to bind");

        if (socktype == SOCK_STREAM && listen(m_fd, 1) < 0)
            throw std::system_error(errno, std::system_category(),
                                    "unable to listen on socket");


        m_sa_recv_len = init_sockaddr(rp, &m_sa_recv);
        freeaddrinfo(res);
    }
コード例 #23
0
JNIEXPORT jboolean JNICALL Java_io_netty_channel_epoll_Native_connect(JNIEnv * env, jclass clazz, jint fd, jbyteArray address, jint scopeId, jint port) {
    struct sockaddr_storage addr;
    init_sockaddr(env, address, scopeId, port, &addr);

    int res;
    int err;
    do {
        res = connect(fd, (struct sockaddr *) &addr, sizeof(addr));
    } while (res == -1 && ((err = errno) == EINTR));

    if (res < 0) {
        if (err == EINPROGRESS) {
            // connect not complete yet need to wait for EPOLLOUT event
            return JNI_FALSE;
        }
        throwIOException(env, exceptionMessage("Unable to connect to remote host: ", err));

        return JNI_FALSE;
    }
    return JNI_TRUE;
}
コード例 #24
0
ファイル: client.c プロジェクト: GuillaumeGas/ReseauTP
int main(int argc, char ** argv) {

  int PORT;
  if(argc>1) {
    PORT = atoi(argv[1]);
  } else {
    PORT = 5555;
  }

  int sock = init_socket();
  if(sock == -1) {
    printf("Erreur socket\n");
    return -1;
  } else {
    char * hostname = "127.0.0.1";
    struct sockaddr_in sin = init_sockaddr(hostname, PORT);

    int connexion = connect(sock, (struct sockaddr *)&sin, sizeof(sin));
    if(connexion == -1) {
      printf("Erreur connect()\n");
      return -1;
    } else {

      pthread_t thread;
      pthread_create(&thread, NULL, boucle_recv, (void*)&sock);
      pthread_detach(thread);

      FILE * flux_write = fdopen(sock, "w");
      while(1) {
	char buf[4];
	printf("> ");
	scanf("%s", buf);
        envoyer(buf, sock, flux_write);
      }
    }


  }
    return 0;
}
コード例 #25
0
ファイル: p12-20.c プロジェクト: AKSahai/Linux_Programming
int main(int argc, char **argv) 
{ 
   int sock,n; 
   struct sockaddr_in name; 
   struct hostent *hp;
   char sndmsg[MAXMSG],rcvmsg[MAXMSG];

   /* 檢查參數的合法性 */
   if (argc < 3) {
     fprintf(stderr, "Usage: a.out <hostname> <port>\n");
     exit(1);
   }

   /* 建立資料報套接字 */ 
   if ((sock = socket(AF_INET, SOCK_DGRAM, 0))< 0) 
      err_exit("opening datagram socket"); 

   /* 形成傳送目的地套接字預設位址 */ 
   init_sockaddr(&name, argv[1], argv[2]);
   connect(sock, (struct sockaddr *)&name, sizeof(name)); 

   while(1) {
      printf("Please enter any string(Quit by RETURN key):");
      fgets(sndmsg,MAXMSG,stdin);
      if (sndmsg[0]=='\n')
         break;
      /* 傳送從終端讀入的訊息 */
      if (write (sock, sndmsg, sizeof(sndmsg)) < 0) 
         err_exit("(client) sending error");
      /* 接收並顯示服務傳回的回答 */
      if ((n = read(sock,rcvmsg, MAXMSG)) < 0)
         err_exit("(client) receive error ");
      rcvmsg[n] = 0;
      printf("I received echo: %s",rcvmsg);
   }

   close(sock);
   exit(0); 
}
コード例 #26
0
ファイル: inet_sock.hpp プロジェクト: hundeboll/netmix
    void sock_connect(int socktype = 0)
    {
        struct addrinfo *res, *rp, hints = {0};
        int err;

        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = socktype;
        hints.ai_flags = 0;
        hints.ai_protocol = 0;

        err = getaddrinfo(m_remote_address, m_port, &hints, &res);
        if (err)
            throw std::runtime_error(std::string("unable to resolv host: ") +
                                     gai_strerror(err));

        for (rp = res; rp != NULL; rp = rp->ai_next) {
            m_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if (m_fd < 0)
                continue;

            if (sock_bind_client(rp->ai_family) < 0) {
                close(m_fd);
                continue;
            }

            if (connect(m_fd, rp->ai_addr, rp->ai_addrlen) == 0)
                break;

            close(m_fd);
        }

        if (rp == NULL)
            throw std::system_error(errno, std::system_category(),
                                    "unable to connect");

        m_sa_send_len = init_sockaddr(rp, &m_sa_send);
        freeaddrinfo(res);
    }
コード例 #27
0
ファイル: rrd_helpers.c プロジェクト: yhsong-linux/ganglia
static int
push_data_to_carbon( char *graphite_msg)
{
    int port;
    int carbon_socket;
    struct sockaddr_in server;
    int carbon_timeout = 500;
    int nbytes;
    struct pollfd carbon_struct_poll;
    int poll_rval;
    int fl;

    if (gmetad_config.carbon_port)
        port=gmetad_config.carbon_port;
    else
        port=2003;


    debug_msg("Carbon Proxy:: sending \'%s\' to %s", graphite_msg, gmetad_config.carbon_server);

    /* Create a socket. */
    carbon_socket = socket (PF_INET, SOCK_STREAM, 0);
    if (carbon_socket < 0)
    {
        perror ("socket (client)");
        close (carbon_socket);
        return EXIT_FAILURE;
    }

    /* Set the socket to not block */
    fl = fcntl(carbon_socket,F_GETFL,0);
    fcntl(carbon_socket,F_SETFL,fl | O_NONBLOCK);

    /* Connect to the server. */
    init_sockaddr (&server, gmetad_config.carbon_server, port);
    connect (carbon_socket, (struct sockaddr *) &server, sizeof (server));

    /* Start Poll */
    carbon_struct_poll.fd=carbon_socket;
    carbon_struct_poll.events = POLLOUT;
    poll_rval = poll( &carbon_struct_poll, 1, carbon_timeout ); // default timeout .5s

    /* Send data to the server when the socket becomes ready */
    if( poll_rval < 0 ) {
        debug_msg("carbon proxy:: poll() error");
    } else if ( poll_rval == 0 ) {
        debug_msg("carbon proxy:: Timeout connecting to %s",gmetad_config.carbon_server);
    } else {
        if( carbon_struct_poll.revents & POLLOUT ) {
            /* Ready to send data to the server. */
            debug_msg("carbon proxy:: %s is ready to receive",gmetad_config.carbon_server);
            nbytes = write (carbon_socket, graphite_msg, strlen(graphite_msg) + 1);
            if (nbytes < 0) {
                perror ("write");
                close(carbon_socket);
                return EXIT_FAILURE;
            }
        } else if ( carbon_struct_poll.revents & POLLHUP ) {
            debug_msg("carbon proxy:: Recvd an RST from %s during transmission",gmetad_config.carbon_server);
            close(carbon_socket);
            return EXIT_FAILURE;
        } else if ( carbon_struct_poll.revents & POLLERR ) {
            debug_msg("carbon proxy:: Recvd an POLLERR from %s during transmission",gmetad_config.carbon_server);
            close(carbon_socket);
            return EXIT_FAILURE;
        }
    }
    close (carbon_socket);
    return EXIT_SUCCESS;
}
コード例 #28
0
ファイル: kerberos4-client.c プロジェクト: gokzy/netbsd-src
/* This function has not been changed to deal with NO_SOCKET_TO_FD
   (i.e., systems on which sockets cannot be converted to file
   descriptors).  The first person to try building a kerberos client
   on such a system (OS/2, Windows 95, and maybe others) will have to
   take care of this.  */
void
start_kerberos4_server (cvsroot_t *root, struct buffer **to_server_p,
                        struct buffer **from_server_p)
{
    int s;
    int port;
    struct hostent *hp;
    struct sockaddr_in sin;
    char *hname;

    s = socket (AF_INET, SOCK_STREAM, 0);
    if (s < 0)
	error (1, 0, "cannot create socket: %s", SOCK_STRERROR (SOCK_ERRNO));

    port = get_cvs_port_number (root);

    hp = init_sockaddr (&sin, root->hostname, port);

    hname = xstrdup (hp->h_name);
  
    TRACE (TRACE_FUNCTION, "Connecting to %s(%s):%d",
	   root->hostname,
	   inet_ntoa (sin.sin_addr),
	   port);

    if (connect (s, (struct sockaddr *) &sin, sizeof sin) < 0)
	error (1, 0, "connect to %s(%s):%d failed: %s",
	       root->hostname,
	       inet_ntoa (sin.sin_addr),
	       port, SOCK_STRERROR (SOCK_ERRNO));

    {
	const char *realm;
	struct sockaddr_in laddr;
	int laddrlen;
	KTEXT_ST ticket;
	MSG_DAT msg_data;
	CREDENTIALS cred;
	int status;

	realm = krb_realmofhost (hname);

	laddrlen = sizeof (laddr);
	if (getsockname (s, (struct sockaddr *) &laddr, &laddrlen) < 0)
	    error (1, 0, "getsockname failed: %s", SOCK_STRERROR (SOCK_ERRNO));

	/* We don't care about the checksum, and pass it as zero.  */
	status = krb_sendauth (KOPT_DO_MUTUAL, s, &ticket, "rcmd",
			       hname, realm, (unsigned long) 0, &msg_data,
			       &cred, sched, &laddr, &sin, "KCVSV1.0");
	if (status != KSUCCESS)
	    error (1, 0, "kerberos authentication failed: %s",
		   krb_get_err_text (status));
	memcpy (kblock, cred.session, sizeof (C_Block));
    }

    close_on_exec (s);

    free (hname);

    /* Give caller the values it wants. */
    make_bufs_from_fds (s, s, 0, root, to_server_p, from_server_p, 1);
}
コード例 #29
0
ファイル: web.c プロジェクト: LuizCB/darkbot
int
web_open_socket(char *host, int port)
{
    extern void init_sockaddr (struct sockaddr_in *name, char *host, unsigned short int port);
	
    struct sockaddr_in name;
    struct timeval timeout;
    int result = 0;
    int esc = 0;
    fd_set set;

    if((wsock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
	return ERR_CANT_CONNECT;
    }

    if((result = fcntl(wsock, F_SETFL, O_NONBLOCK)) < 0)
    {
        return ERR_CANT_CONNECT;
    }

    init_sockaddr (&name, host, port);
	
    if(connect(wsock, (struct sockaddr *) & name, sizeof(name)) != -1)
    {
        return ERR_CANT_CONNECT;
    }

    if(errno != EINPROGRESS)
    {
        return ERR_CANT_CONNECT;
    }

    while(!esc)
    {
	timeout.tv_sec = 10;
	timeout.tv_usec = 0;

	FD_ZERO(&set);
	FD_SET(wsock, &set);

	switch(select(FD_SETSIZE, (fd_set *) 0, &set, (fd_set *) 0, &timeout))
        {
	    case 0:
		return ERR_TIMED_OUT;

	    case -1:
		break;

	    default:
		esc++;

		switch(getsockopt(wsock, SOL_SOCKET, SO_ERROR, &sockerr, &optlen)) 
		{
		    case -1:
			break;

		    case 0:
			switch(sockerr) 
			{
			    case ECONNREFUSED:
				break;
							
			    case EADDRNOTAVAIL:
				break;

			    case ENETUNREACH:
				break;

			    case SUCCESS: 
				if((result = fcntl(wsock, F_SETFL, 0)) < 0)
                                {
                                    return ERR_CANT_CONNECT;
   				}
				return SUCCESS;
			}
		}
	}
    }
    return SUCCESS;
}
コード例 #30
0
int main(){
char address[100],buffer[5000],user_name[100],b[5000],terminate[]="bye\n";
int sock_server,sock_client_init,sock_client,already_connected=0,e;
struct sockaddr_in servername;
struct sockaddr_in client;
printf("please press \"x\" to exit...");
printf("\n enter your name(no space allowed) to start chat : ");
scanf("%s",user_name);
sock_server=create_socket(2345);

sock_client_init=socket(PF_INET,SOCK_STREAM,0);
listen(sock_server,1);
init_sockaddr(&servername,"127.0.0.1",2345);

fd_set readfdset,writefdset;
FD_ZERO(&readfdset);
FD_ZERO(&writefdset);
FD_SET(0,&readfdset);
FD_SET(sock_server,&readfdset);

while(1){
FD_ZERO(&readfdset);
FD_SET(0,&readfdset);
FD_SET(sock_server,&readfdset);
if(already_connected==1){
FD_SET(sock_client,&readfdset);
FD_SET(sock_client,&writefdset);
}
if(already_connected==2){
FD_SET(sock_client_init,&readfdset);
FD_SET(sock_client_init,&writefdset);
}
select(FD_SETSIZE,&readfdset,NULL,NULL,NULL);
//server to accept connection
if(FD_ISSET(sock_server,&readfdset)){
sock_client=accept(sock_server,(struct sockaddr *)NULL ,NULL);
if(sock_client!=-1)
already_connected=1;
FD_SET(sock_client,&readfdset);
FD_SET(sock_client,&writefdset);
}
//if connected and data available then read

if(already_connected==1 && FD_ISSET(sock_client,&readfdset)){
read(sock_client,buffer,sizeof(buffer));
if(strcmp(buffer,terminate)==0){
    printf("seems ur friend has gone off line.........");
            break;
        }
printf(ANSI_COLOR_RED"%s"ANSI_COLOR_RESET ,buffer);
}

if((already_connected==2) && FD_ISSET(sock_client_init,&readfdset) ){
read(sock_client_init,buffer,sizeof(buffer));
if(strcmp(buffer,terminate)==0){
    printf("seems ur friend has gone off line.........");
    break;
        }
printf(ANSI_COLOR_YELLOW"%s"ANSI_COLOR_RESET ,buffer);
}

if(FD_ISSET(0,&readfdset)){
    memset(b,'\0',sizeof(b));
    memset(buffer,'\0',sizeof(buffer));
    read(0,b,sizeof(b));
    strcat(buffer,user_name);
    strcat(buffer," : ");
    strcat(buffer,b);
    if(strcmp(b,terminate)==0){
    printf("OK terminating all connections.........");
    memset(buffer,'\0',sizeof(buffer));
    strcpy(buffer,terminate);
        }
    if (already_connected==0){
            connect(sock_client_init,(struct sockaddr *)&servername,(socklen_t)sizeof(servername));
            FD_SET(sock_client_init,&readfdset);
            FD_SET(sock_client_init,&writefdset);
            already_connected=2;
        }
    if(already_connected==1){
            write(sock_client,buffer,strlen(buffer)+1);
        }
    if(already_connected==2 ){
       write(sock_client_init,buffer,strlen(buffer)+1);
       }
       if(strcmp(b,terminate)==0)
        break;
    }
}


shutdown(sock_server,2);
if(already_connected==1)
shutdown(sock_client,2);
if(already_connected==2)
shutdown(sock_client_init,2);
printf("done ,see u soon....\n designed by ..Sutirtha Ghosh.........\n");
return 0;}