Loading...
More C Posts
// Server side implementation of UDP client-server model#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <arpa/inet.h>#include <netinet/in.h>#define PORT 8008#define RECIEVE_BUFFER_SIZE 1024// Driver codeint main() {//Create a UDP socket//int socket(int domain, int type, int protocol);//Domain is the place where the data goes. AF_BLUETOOTH, AF_INET6, AF_UNIX is local communication between different programs//Type is the type of connection, so connection based (TCP), connectionless (UDP) or somewhere in between or beyond//Protocol is an enum or flags that give some more options specific to that type. For SOCK_STREAM, you can force it to use SCTP instead of TCP. For SOCK_RAW, it can give you control over the ip frame, and even the ethernet frame.//So this function makes a file descriptor to an IPV4 UDP 'connection' with no options.int sockfd = socket(AF_INET, SOCK_DGRAM, 0);// Creating socket file descriptorif ( sockfd < 0) {perror("socket creation failed");exit(EXIT_FAILURE);}struct sockaddr_in serverAddress;memset(&serverAddress, 0, sizeof(serverAddress));// Filling server informationserverAddress.sin_family = AF_INET; // IPv4serverAddress.sin_addr.s_addr = INADDR_ANY;serverAddress.sin_port = htons(PORT);// Bind the socket with the server addressif(bind(sockfd, (const struct sockaddr*)&serverAddress, sizeof(serverAddress))){ //Bind returns 0 if succeeded, or -1 if failed. -1 is still true.perror("bind failed");exit(EXIT_FAILURE);}struct sockaddr_in clientAddress; unsigned int clientAddressSize = sizeof(clientAddress);memset(&clientAddress, 0, clientAddressSize);char buffer[RECIEVE_BUFFER_SIZE];while(1){int bytesRecieved = recvfrom(sockfd, (char*)buffer, RECIEVE_BUFFER_SIZE, MSG_WAITALL, (struct sockaddr*) &clientAddress, &clientAddressSize); //sets clientAddress to the client's address and the new sizebuffer[bytesRecieved] = '\0';//printf("Client : %s\n", buffer);//The client might be like PINGUIN or something, but this is to ensure PING\n\r also gets acceptedif(bytesRecieved >= 4 && (strncmp("PING", buffer, 4) == 0)){const char* responseMessage = "PONG";sendto(sockfd, (const char*)responseMessage, strlen(responseMessage), MSG_CONFIRM, (const struct sockaddr*) &clientAddress, clientAddressSize);//printf("Hello message sent.\n");}else{printf("Server bytes recieved: %d\nServer message recieved: %s", bytesRecieved, buffer);}}return 0;}
#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main() {pid_t pid; /* could be int */int i;pid = fork();printf("PID=%d\n", pid);if (pid > 0) {/* parent */for (i = 0; i < 10; i++)printf("\t\t\tPARENT %d\n", i);} else {/* child */for (i = 0; i < 10; i++)printf("CHILD %d\n", i);}return 0;}
//Leif Messingerconst int BUZZER_PIN = 8;const int BUTTON_PIN = 2;const int BUTTON_PINMODE = INPUT_PULLUP;#define DEBOUNCE_DELAY 50class Button{private:short buttonPin;bool buttonState;bool lastButtonState;int lastDebounceTime;public:Button(short buttonPin): buttonState(HIGH), lastButtonState(LOW), lastDebounceTime(millis()){this->buttonPin = buttonPin;}bool checkForPress(const bool desiredState){ //Returns true if button pressedbool reading = (bool)digitalRead(buttonPin);// check to see if you just pressed the button// (i.e. the input went from LOW to HIGH), and you've waited long enough// since the last press to ignore any noise:// If the switch changed, due to noise or pressing:if (reading != lastButtonState) {// reset the debouncing timerlastDebounceTime = millis();}else if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {// whatever the reading is at, it's been there for longer than the debounce// delay, so take it as the actual current state:// if the button state has changed:if (reading != buttonState) {buttonState = reading;// only toggle the LED if the new button state is HIGHif (buttonState == desiredState) {return true;}}}// save the reading. Next time through the loop, it'll be the lastButtonState:lastButtonState = reading;return false;}void waitForPress(const bool desiredState){while(!checkForPress(desiredState));}};class Note{public:short frequency; //Short max is ~ 30k, so way higher than you can hearshort lag; //Also 30k ms is 30 secondsfloat sustainPercentage;};const short normalBeatLength = 500;const short wholeNote = 4*normalBeatLength;const short halfNote = 2*normalBeatLength;const short dottedQuarterNote = normalBeatLength + (normalBeatLength / 2);const short quarterNote = normalBeatLength;const short dottedEighthNote = ((3 * normalBeatLength) / 4);const short eighthNote = normalBeatLength/ 2;const short sixteenthNote = normalBeatLength / 4;const float normalSustainLength = .25;void beep(const Note& note){ //It might go terribly wrong if you try to beep two tones at the same time.tone(BUZZER_PIN, note.frequency);delay(note.lag * note.sustainPercentage);noTone(BUZZER_PIN);delay(note.lag * (1.0 - note.sustainPercentage));}Note song[] = {{(int)523.25, halfNote, normalSustainLength},{(int)392, eighthNote, normalSustainLength},{(int)523.25, quarterNote, normalSustainLength},{(int)392, dottedEighthNote, normalSustainLength},{(int)440.00, sixteenthNote, normalSustainLength},{(int)493.88, quarterNote, normalSustainLength},{(int)329.63, eighthNote, normalSustainLength},{(int)329.63, eighthNote, normalSustainLength},{(int)440.00, quarterNote, normalSustainLength},{(int)392, dottedEighthNote, normalSustainLength},{(int)349.23, sixteenthNote, normalSustainLength},{(int)392, quarterNote, normalSustainLength},{(int)261.63, dottedEighthNote, normalSustainLength},{(int)261.63, sixteenthNote, normalSustainLength},{(int)293.66, quarterNote, normalSustainLength},{(int)293.66, dottedEighthNote, normalSustainLength},{(int)329.63, sixteenthNote, normalSustainLength},{(int)349.23, quarterNote, normalSustainLength},{(int)349.23, dottedEighthNote, normalSustainLength},{(int)392.00, sixteenthNote, normalSustainLength},{(int)440.00, quarterNote, normalSustainLength},{(int)493.88, eighthNote, normalSustainLength},{(int)523.25, eighthNote, normalSustainLength},{(int)587.33, dottedQuarterNote, normalSustainLength},{(int)392, eighthNote, normalSustainLength},{(int)659.25, quarterNote, normalSustainLength},{(int)587.33, dottedEighthNote, normalSustainLength},{(int)523.25, sixteenthNote, normalSustainLength},{(int)587.33, quarterNote, normalSustainLength},{(int)493.88, eighthNote, normalSustainLength},{(int)392, eighthNote, normalSustainLength},{(int)523.25, quarterNote, normalSustainLength},{(int)493.88, dottedEighthNote, normalSustainLength},{(int)440.00, sixteenthNote, normalSustainLength},{(int)493.88, quarterNote, normalSustainLength},{(int)329.63, eighthNote, normalSustainLength},{(int)329.63, eighthNote, normalSustainLength},{(int)440.00, quarterNote, normalSustainLength},{(int)392, dottedEighthNote, normalSustainLength},{(int)349.23, sixteenthNote, normalSustainLength},{(int)392, quarterNote, normalSustainLength},{(int)261.63, dottedEighthNote, normalSustainLength},{(int)261.63, sixteenthNote, normalSustainLength},{(int)523.25, quarterNote, normalSustainLength},{(int)493.88, dottedEighthNote, normalSustainLength},{(int)440.00, sixteenthNote, normalSustainLength},{(int)392.00, halfNote, normalSustainLength * .5},};size_t songLength = (sizeof(song) / sizeof(Note));void playSong(){for(size_t pos = 0; pos < songLength; ++pos){const Note& bruh = song[pos];beep(bruh);}}void setup() {const int BUZZER_PIN = 8;pinMode(BUZZER_PIN, OUTPUT);pinMode(BUTTON_PIN, BUTTON_PINMODE);playSong();}Button button(BUTTON_PIN);void loop() {button.waitForPress(LOW);// read the state of the switch into a local variable:playSong();}
#include <stdio.h>#include <stdlib.h>// give an array of identical coins (ints), represented by 1's and one 2// we can find the heavy coin (2) by summing the contents of the thirdsint sum_subarr(int arr[], int l, int r){int sum = 0;for(int i = l; i <= r; i++){sum += arr[i];}return sum;}int heavy_coin(int arr[], int l, int r){if(r == l){return r;}int midl = l + (r - l)/3;int midr = r - (r - l)/3;int lw = sum_subarr(arr, l, midl);int mw = sum_subarr(arr, midl + 1, midr);if ( lw > mw ){return heavy_coin(arr, l, midl);}else if ( lw < mw ){return heavy_coin(arr, midl + 1, midr);}else{return heavy_coin(arr, midr + 1, r);}}int main(int argc, char *argv[]){int arr[] = {1,1,1,1,2,1,1,1,1};int l = 0;int r = 8;int res = -1;res = heavy_coin(arr, l, r);printf("Hevy coin is at index: %d\n", res);return EXIT_SUCCESS;}
// compile: gcc socketTCPServer.c -o socketTCPServer.out// usage : ./socketTCPServer.out port// Server#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <sys/types.h>int main(int argc, char *argv[]){int listenfd = 0, connfd = 0, cli_size, portno;struct sockaddr_in serv_addr, cli_addr;char sendBuff[1025];if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){printf("socket error\n");exit(EXIT_FAILURE);}memset(&serv_addr, '0', sizeof(serv_addr));memset(sendBuff, '0', sizeof(sendBuff));serv_addr.sin_family = AF_INET;serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);portno = atoi(argv[1]);serv_addr.sin_port = htons(portno);const int on = 1;setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));if(bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1){printf("bind error\n");exit(EXIT_FAILURE);}if(listen(listenfd, 5) == -1){printf("listen error\n");exit(EXIT_FAILURE);}while(1){cli_size = sizeof(cli_addr);if((connfd = accept(listenfd, (struct sockaddr*)&cli_addr, &cli_size)) == -1){printf("accept error\n");exit(EXIT_FAILURE);}strcpy(sendBuff, "Server Message: SUCCESS\n");write(connfd, sendBuff, strlen(sendBuff));close(connfd);sleep(1);}return 0;}
// Server side implementation of UDP client-server model#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <arpa/inet.h>#include <netinet/in.h>#define PORT 8008#define RECIEVE_BUFFER_SIZE 1024const char* responseMessage = "Hello from server";// Driver codeint main() {//Create a UDP socket//int socket(int domain, int type, int protocol);//Domain is the place where the data goes. AF_BLUETOOTH, AF_INET6, AF_UNIX is local communication between different programs//Type is the type of connection, so connection based (TCP), connectionless (UDP) or somewhere in between or beyond//Protocol is an enum or flags that give some more options specific to that type. For SOCK_STREAM, you can force it to use SCTP instead of TCP. For SOCK_RAW, it can give you control over the ip frame, and even the ethernet frame.//So this function makes a file descriptor to an IPV4 UDP 'connection' with no options.int sockfd = socket(AF_INET, SOCK_DGRAM, 0);// Creating socket file descriptorif ( sockfd < 0) {perror("socket creation failed");exit(EXIT_FAILURE);}struct sockaddr_in serverAddress;memset(&serverAddress, 0, sizeof(serverAddress));// Filling server informationserverAddress.sin_family = AF_INET; // IPv4serverAddress.sin_addr.s_addr = INADDR_ANY;serverAddress.sin_port = htons(PORT);// Bind the socket with the server addressif(bind(sockfd, (const struct sockaddr*)&serverAddress, sizeof(serverAddress))){ //Bind returns 0 if succeeded, or -1 if failed. -1 is still true.perror("bind failed");exit(EXIT_FAILURE);}struct sockaddr_in clientAddress; unsigned int clientAddressSize = sizeof(clientAddress);memset(&clientAddress, 0, clientAddressSize);char buffer[RECIEVE_BUFFER_SIZE];int bytesRecieved = recvfrom(sockfd, (char*)buffer, RECIEVE_BUFFER_SIZE, MSG_WAITALL, (struct sockaddr*) &clientAddress, &clientAddressSize); //sets clientAddress to the client's address and the new sizebuffer[bytesRecieved] = '\0';printf("Client : %s\n", buffer);sendto(sockfd, (const char*)responseMessage, strlen(responseMessage), MSG_CONFIRM, (const struct sockaddr*) &clientAddress, clientAddressSize);printf("Hello message sent.\n");return 0;}