# c-socket-lib **Repository Path**: zhufengGNSS/c-socket-lib ## Basic Information - **Project Name**: c-socket-lib - **Description**: A socket library for C that makes writing socket programs a cinch. - **Primary Language**: C - **License**: GPL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 4 - **Forks**: 1 - **Created**: 2020-04-12 - **Last Updated**: 2022-12-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README c-socket-lib ============ A socket library for C that makes writing socket programs a cinch. The library models the simplicity of Python's socket library API. If you can create a socket in Python, you can just as easily create one using this class! Currently the library will only work on Linux. TODO ------------- * Support Windows * Implement raw sockets How to use this library ------------- This library depends on class.c from my [c-functions](https://github.com/hongmeister/c-functions) library. Instantiate the socket object: Socket *s = init_socket(AF_INET, SOCK_STREAM); Where AF_INET is the address family, and SOCK_STREAM is the socket type. Then either connect to act as a client, or bind, listen, and accept to act as a server. Use send and recv to send and receive data to/from the client/server. When you're done, destroy the object: socket_close(s); Sample echo server ------------- These examples are also in the tests/ directory. The server: #include #include #include #include "socket.h" int main() { char buff[100]; int bytes; Socket *s = init_socket(AF_INET, SOCK_STREAM); s->bind(s, NULL, 12345); s->listen(s, 5); ClientAddr client_addr; Socket *c = s->accept(s, &client_addr); printf("Client connected at %s:%d\n", client_addr.ip_addr, client_addr.port); while (1) { c->recv(c, buff, sizeof(buff)); printf("Got: %s\n", buff); c->send(c, buff); printf("Sending: %s\n", buff); } socket_close(c); socket_close(s); } The client: #include #include #include #include "socket.h" int main() { int bytes; char buff[100]; Socket *s = init_socket(AF_INET, SOCK_STREAM); s->connect(s, "127.0.0.1", 12345); while (1) { memset(buff, 0, sizeof(buff)); printf(">> "); if (fgets(buff, sizeof(buff), stdin) == NULL) { perror("fgets error"); break; } s->send(s, buff); s->recv(s, buff, sizeof(buff)); printf("Received: %s\n", buff); } socket_close(s); }