// tcp.c
// $Id: tcp.c,v 1.2 2007/10/17 11:24:23 sendan Exp $
// masashi shimakura

#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in_systm.h>
#include<netinet/in.h>
#include<netinet/ip.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include <fcntl.h>


#include"proxy.h"
// #include"almemsys.h"

extern struct my_sock ip;
extern struct buf_data bf;

/*
int socket_bind2(int, char []);
int socket_connect2(int, char []);
int socket_accept2(int);
*/


/*------------------ BIND ----------------------*/
int socket_bind2(int port, char ip_addr[])
{
if((ip.in.ls = socket(AF_INET, SOCK_STREAM, 0))==-1){
   fprintf(stderr,"----soket-err----\n");
   exit(1);
   }

ip.in.my_addr.sin_family = AF_INET;
ip.in.my_addr.sin_port = htons(port);
ip.in.my_addr.sin_addr.s_addr = inet_addr(ip_addr);

if(bind(ip.in.ls, (struct sockaddr *) &ip.in.my_addr, sizeof(ip.in.my_addr)) == -1){
   fprintf(stderr,"----bind-err---\n");
   close(ip.in.ls);
   exit(1);
   }

if((listen(ip.in.ls,0))==-1){
   fprintf(stderr,"----Listen-err---\n");
   close(ip.in.ls);
   exit(1);
   }
return 0;
}




/*----------------------- CONNECT --------------------*/
int socket_connect2(int port, char ip_addr[], int count)
{

if((ip.out.sk[count] = socket(AF_INET, SOCK_STREAM, 0))==-1){
   fprintf(stderr,"----soket-err----\n");
   exit(1);
   }

ip.out.my_addr.sin_family = AF_INET;
ip.out.my_addr.sin_port = htons(port);
ip.out.my_addr.sin_addr.s_addr = inet_addr(ip_addr);

if(connect(ip.out.sk[count], (struct sockaddr *) &ip.out.my_addr, sizeof(ip.out.my_addr)) == -1){
   fprintf(stderr,"----connect-err---\n");
   return -1;
   }
return 0;
}




/*--------------------- ACCEPT -------------------*/
int socket_accept2(int count)
{
ip.in.my_addrlen = sizeof(ip.in.my_addr);
if((ip.in.sk[count]=accept(ip.in.ls, (struct sockaddr *) &ip.in.my_addr, &ip.in.my_addrlen)) == -1){
   fprintf(stderr,"--- accept-err ---\n");
   fprintf(stderr,"The maximum, connected number of servers is exceeded. %d\n", count);
   close(ip.in.ls);
   exit(1);
   }
else {
   ip.fdno = count;
   }
return 0;
}




