Add socket and IPv4 support for x86_64
This commit is contained in:
92
socktest.c
Normal file
92
socktest.c
Normal file
@@ -0,0 +1,92 @@
|
||||
#include "sys.h"
|
||||
#include "int.h"
|
||||
#include "net/ipv4.h"
|
||||
|
||||
int main() {
|
||||
char recvBuff[4096];
|
||||
int socket_fd, connection_fd;
|
||||
int c;
|
||||
struct sockaddr_in server, client;
|
||||
server.sin_family = AF_INET;
|
||||
server.sin_addr.s_addr = INADDR_ANY;
|
||||
//server.sin_port = htons( 6969 );
|
||||
server.sin_port = 0x391b;
|
||||
|
||||
// Create the socket
|
||||
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
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 | SO_REUSEPORT, &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
|
||||
c = sizeof(struct sockaddr_in);
|
||||
connection_fd = accept(socket_fd, (void *)&client, (uint64_t*)&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(;;) {
|
||||
int64_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;
|
||||
}
|
||||
|
||||
void _start() {
|
||||
exit(main());
|
||||
}
|
||||
Reference in New Issue
Block a user