minimalc/socktest.c

92 lines
2.1 KiB
C

#include "sys.h"
#include "int.h"
#include "net/ipv4.h"
int main() {
char recvBuff[4096];
int socket_fd, connection_fd;
struct sockaddr_in server, client;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
#if defined(__mips__)
server.sin_port = 6969;
#else
server.sin_port = 0x391b;
#endif
// Create the socket
socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (socket_fd < 0) {
write(STDERR, "Socket error\n", 13);
close(socket_fd);
return 1;
}
// Set socket options
int opt = 1;
if(0 > setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
write(STDERR, "Socket error\n", 13);
close(socket_fd);
return 2;
}
// Bind the socket
if( bind(socket_fd, (struct sockaddr *)&server, sizeof(server)) < 0) {
write(STDERR, "Socket error\n", 13);
close(socket_fd);
return 3;
}
// Listen for incoming connections
if (listen(socket_fd, 3) < 0) {
return 4;
}
write(STDOUT, "Waiting for incoming connections...\n", 36);
// Get the new connection
socklen_t c = sizeof(struct sockaddr_in);
connection_fd = accept(socket_fd, (void *)&client, &c);
write(STDOUT, "Got new connection\n", 19);
if(connection_fd < 0) {
write(STDERR, "Connection error\n", 17);
close(connection_fd);
close(socket_fd);
return 5;
}
//char *client_ip = inet_ntoa(client.sin_addr);
//int client_port = ntohs(client.sin_port);
//printf("Connection accepted from %s:%d\n", client_ip, client_port);
// Send stuff
write(STDOUT, "Connection Established!\n", 24);
if( send(connection_fd, "Connection Established!\n", 24, 0) < 0) {
write(STDERR, "Connection error\n", 17);
close(connection_fd);
close(socket_fd);
return 6;
}
// Recieve stuff
write(STDOUT, "Recieving data...\n", 18);
for(;;) {
ssize_t incoming = recv(connection_fd, recvBuff, 4096, 0);
if( incoming < 0) {
write(STDERR, "Connection error\n", 17);
close(connection_fd);
close(socket_fd);
return 7;
}if(incoming == 0) break;
// Print the recieved data
write(STDOUT, recvBuff, incoming);
}
write(STDOUT, "Closing connection\n", 19);
close(connection_fd);
close(socket_fd);
return 0;
}