socket/socket.cpp

146 lines
2.5 KiB
C++

#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "socket.h"
client_tcp::client_tcp(int client)
{
// Set the client
sock = client;
}
client_tcp::client_tcp(const char *name, int port)
{
// Create the TCP socket
if((sock=socket(AF_INET, SOCK_STREAM, 0))<0)
{
status = 1;
return;
}
// Set reuse_addr
int enable = 1;
if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
{
status = 2;
return;
}
// Get the server
if((server = gethostbyname(name)) == NULL)
{
status = 3;
return;
}
// Zero out the data
bzero((char *) &serv_addr, sizeof(serv_addr));
// Set some settings
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
// Copy the server address to the serv_addr variable
bcopy(
(char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length
);
// Try connecting to the server
if (connect(sock, (struct sockaddr*)& serv_addr, sizeof(serv_addr)) < 0)
{
status = 4;
return;
}
// Set the status
status = 0;
}
client_tcp::~client_tcp()
{
// Close the socket
close(sock);
}
char* client_tcp::recv(int size)
{
// Make the buffer
char* buffer = new char[size+1]();
// Clear the buffer
bzero((char*)buffer, size);
// Get the data from the client
bzero((char*)buffer, size);
read(sock, buffer, size);
// Return the data
return buffer;
}
bool client_tcp::send(const char* data, int size)
{
// Send the data
write(sock, data, size);
}
server_tcp::server_tcp(int port)
{
// Create the TCP socket
if((sock=socket(AF_INET, SOCK_STREAM, 0))<0)
{
status = 1;
return;
}
// Zero out the data
bzero((char *) &serv_addr, sizeof(serv_addr));
// Set some config
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
// Bind the port
if(bind(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
status = 2;
return;
}
// Set status of 0
status = 0;
}
server_tcp::~server_tcp()
{
// Close the socket
close(sock);
}
client_tcp server_tcp::cliaccept()
{
// Client address
struct sockaddr_in cli_addr;
// Listen for new connections
listen(sock,5);
// Get the client size
socklen_t clilen = sizeof(cli_addr);
// Accept a new client
int newsock = accept(sock, (struct sockaddr *) &cli_addr, &clilen);
// Return the client
return client_tcp(newsock);
}