I am trying to use the same pointer twice, like this:
void* pointer = (char*) malloc(15);
pointer = "Patricia";
printf("%s", pointer);
pointer = "John";
printf("%s", pointer);
but the output I'm receiving is this:
Patricia
Johnicia
Here is the full code (the client script is a python script so I don't find it appropriate to post here)(the John and Patricia are examples of usernames the client might enter):
#define MAXCLIENTS 256
#define MAXMSG 269
void forward(int clientslist[MAXCLIENTS], char* msg) {
int x;
for (x=0; x < MAXCLIENTS; x++){
send(clientslist[x], msg, MAXMSG, 0);
}
return;
}
int main(){
#define PORT 5943
int s = socket(AF_INET, SOCK_STREAM, 0);
int clients[MAXCLIENTS];
int clientcounter = 0;
fd_set socketlist, readlist;
FD_ZERO(&socketlist);
FD_SET(s, &socketlist);
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = INADDR_ANY;
bind(s, (struct sockaddr*) &server, sizeof(server));
listen(s, MAXCLIENTS);
int clientsocket;
int i;
void* msg = (char *) malloc(MAXMSG);
void* usr = (char*) malloc(10);
while (1){
readlist = socketlist;
select(FD_SETSIZE, &readlist, NULL, NULL, NULL);
for (i=0; i<FD_SETSIZE; i++){
if(FD_ISSET(i, &readlist)){
if (i == s){
clientsocket = accept(s, NULL, NULL);
FD_SET(clientsocket, &socketlist);
clients[clientcounter] = clientsocket;
clientcounter++;
recv(clientsocket, usr, 10, 0);
printf("Connection received from %s\n", usr);
} else {
recv(i, msg, MAXMSG, 0);
forward(clients, msg);
}
}
}
}
return 0;
}
How do I fix this??
Thanks
recv returns the number of bytes read, and you just need to add a null terminator. eg:
ssize_t rc;
rc = recv(clientsocket, usr, 9, 0);
if( rc >= 0 )
usr[rc] = '\0';
Note that I've reduced the length argument in the call to recv to ensure that there is space for the terminator. If you expect to receive messages of length 10, you would want to allocate at least 11 bytes for usr. However, with buffers that small, it would probably be cleaner to use an array and do:
char usr[11];
ssize_t rc;
rc = recv(clientsocket, usr, sizeof usr - 1, 0);
if( rc >= 0 )
usr[rc] = '\0';
Related
How can I send and receive a long array of integers using TCP sockets?
In the case of short array, the reception is possible using the function recv(.., 4*size of array) one time, however when the size of array is too long, I can't receive data correctly.
int main(void)
{
int listenfd = 0, connfd = 0;
int i,j,x;
int fd;
unsigned int *pic;
struct sockaddr_in serv_addr;
char *recvBuff;
clock_t t;
//Allocate memory for a 24-bit 640x480 rgb image
pic = (int*)malloc(10*sizeof(int));
recvBuff = (char*)malloc(1*sizeof(char));
for(i = 0; i < 10 ; i++){
pic[i] = 20;
}
//Create the TCP socket
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(pic, '0', sizeof(pic));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(7); // la valeur du port
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(listenfd, 10);
//fprintf(stdout,"End Creating Socket4\n");
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
while(1)
{
recv(connfd,recvBuff, sizeof(char),MSG_WAITALL);
//printf("BUFF: %s\n",recvBuff);
//Wait for client request
if(strcmp(recvBuff,"A")){
printf("Error in input\n");
}else
write(connfd, pic, 921600);
}
close(connfd);
}
In the case of short array, the reception is possible using the function recv(.., 4*size of array) one time
That is not guaranteed. Any call to recv() can return fewer bytes than requested, even as few as just 1 byte. So you always need to call recv() in a loop until you have actually received as many bytes as are you expecting, eg:
ssize_t recv_all(int skt, void *buf, size_t bufsize)
{
char *ptr = (char*) buf;
while (bufsize > 0)
{
ssize_t recvd = recv(skt, ptr, bufsize, 0);
if (recvd <= 0) return recvd;
ptr += recvd;
bufsize -= recvd;
}
return 1;
}
And then you can call it like this:
int32_t *arr = (int32_t*) malloc(sizeof(int32_t) * count);
...
if (recv_all(..., arr, sizeof(int32_t) * count) <= 0)
{
// error, or peer disconnected...
}
else
{
// use arr as needed...
}
You should do the same thing for send() too, eg:
ssize_t send_all(int skt, const void *buf, size_t bufsize)
{
const char *ptr = (const char*) buf;
while (bufsize > 0)
{
ssize_t sent = send(skt, ptr, bufsize, 0);
if (sent < 0) return sent;
ptr += sent;
bufsize -= sent;
}
return 0;
}
int32_t *arr = (int32_t*) malloc(sizeof(int32_t) * count);
...
if (send_all(..., arr, sizeof(int32_t) * count) < 0)
{
// error...
}
else
{
// arr sent in full...
}
First of all, it's worth noting that recv() doesn't care at all about the type of data it receives, only about its size.
So all you need is a function that calls recv() in a loop until it receives all of the requested data
// Returns the number of bytes read, or -1 in the case of an error
ssize_t recv_all(const int sock, void * const buf, const size_t n)
{
ssize_t len = 0;
ssize_t total_read = 0;
while (n > (size_t)total_read)
{
len = recv(sock, (char *)buf + total_read, n - total_read, MSG_WAITALL);
switch (len)
{
case -1:
return -1;
case 0:
break;
default:
total_read += len;
}
}
return total_read;
}
I am new to C programming (as you can probably tell from the code) I wanted to make a function to send data instead of putting it inline, when it's inline it works but when it's a function it fails and I don't know why. The code is running on an ESP32 chip.
Inline
void wifi_scan(void) {
uint16_t number = DEFAULT_SCAN_LIST_SIZE;
wifi_ap_record_t ap_info[DEFAULT_SCAN_LIST_SIZE];
uint16_t loop_count = 0;
uint16_t seen_before = 0;
const char *ch_arr[18] = {};
const char * ( *ptr )[18] = &ch_arr;
const char *prev_ch_arr[18] = {};
const char * ( *prev_ptr )[18] = &prev_ch_arr;
while (loop_count < 9) {
uint16_t ap_count = 0;
memset(ap_info, 0, sizeof(ap_info));
esp_wifi_set_mode(WIFI_MODE_STA);
esp_wifi_start();
esp_wifi_scan_start(NULL, true);
esp_wifi_scan_get_ap_records(&number, ap_info);
esp_wifi_scan_get_ap_num(&ap_count);
//char rx_buffer[128];
char host_ip[] = HOST_IP_ADDR;
int addr_family = 0;
int ip_protocol = 0;
struct sockaddr_in dest_addr;
dest_addr.sin_addr.s_addr = inet_addr(host_ip);
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(PORT);
addr_family = AF_INET;
ip_protocol = IPPROTO_IP;
int sock = socket(addr_family, SOCK_STREAM, ip_protocol);
connect(sock, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in6));
for (int i = 0; (i < DEFAULT_SCAN_LIST_SIZE) && (i < ap_count); i++) {
( *ptr )[i] = &ap_info[i].ssid;
char buf[60];
//snprintf(buf, sizeof buf, "%s:%s:%d", SYSTEM_TAG, ap_info[i].ssid, ap_info[i].rssi);
snprintf(buf, sizeof buf, "%s#%02x:%02x:%02x:%02x:%02x:%02x#%s#%d$", SYSTEM_TAG, ap_info[i].bssid[0], ap_info[i].bssid[1], ap_info[i].bssid[2], ap_info[i].bssid[3], ap_info[i].bssid[4], ap_info[i].bssid[5], ap_info[i].ssid, ap_info[i].rssi);
ESP_LOGI("LOG", "%02x:%02x:%02x:%02x:%02x:%02x#%s#%d$", ap_info[i].bssid[0], ap_info[i].bssid[1], ap_info[i].bssid[2], ap_info[i].bssid[3], ap_info[i].bssid[4], ap_info[i].bssid[5], ap_info[i].ssid, ap_info[i].rssi);
char* *input = buf;
unsigned char output[64];
size_t outlen;
mbedtls_base64_encode(output, 64, &outlen, input, strlen(input));
//static const char *payload = "YES";
send(sock, output, strlen((const char*) output), 0);
send(sock, "\n", strlen("\n"), 0);
}
shutdown(sock, 0);
close(sock);
loop_count++;
}
get_sleep_time();
prepareAndGoToDeepSleep();
}
The function I want to use
void send_data( char buf ) {
char host_ip[] = HOST_IP_ADDR;
int addr_family = 0;
int ip_protocol = 0;
struct sockaddr_in dest_addr;
dest_addr.sin_addr.s_addr = inet_addr(host_ip);
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(PORT);
addr_family = AF_INET;
ip_protocol = IPPROTO_IP;
int sock = socket(addr_family, SOCK_STREAM, ip_protocol);
connect(sock, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in6));
char* *input = buf;
unsigned char output[64];
size_t outlen;
mbedtls_base64_encode(output, 64, &outlen, input, strlen(input));
send(sock, output, strlen((const char*) output), 0);
send(sock, "\n", strlen("\n"), 0);
shutdown(sock, 0);
close(sock);
}
I would like to use it like this
( *ptr )[i] = &ap_info[i].ssid;
char buf[60];
snprintf(buf, sizeof buf, "%s#%02x:%02x:%02x:%02x:%02x:%02x#%s#%d$", SYSTEM_TAG, ap_info[i].bssid[0], ap_info[i].bssid[1], ap_info[i].bssid[2], ap_info[i].bssid[3], ap_info[i].bssid[4], ap_info[i].bssid[5], ap_info[i].ssid, ap_info[i].rssi);
send_data(buf);
IT compiles ok but when I run the code it just fails no console error just CPU reboots
rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:5668
load:0x40078000,len:14344
load:0x40080400,len:3748
0x40080400: _init at ??:?
Im writing a program which connects to a browser and sends the http request from the browser to a server, and then sends the response back to the browser, which loads the page with some of the content. My program sends things successfully and loads pages, but does not run continuously and will crash after a random amount of time- sometimes 10 seconds of running sometimes 1 minute. I want this proxy to be able to run forever. Below is how I have structured my code. I have included the recv and write section which I think is causing my errors in full. I am pretty new to socket programming and c In general and looking for some tips on my structure and anything I may have missed.
int main(int argc, char *argv[])
{
char ip[40]
char *host = argv[1];
char *port_s = argv[2];
int err;
int socket_browser, socket_newBrowser, c;
struct sockaddr_in server, client;
int n;
socket_browser= socket(AF_INET, SOCK_STREAM, 0);
if (socket_browser < 0)
{
printf("Could not create socket");
}
if (err = bind(socket_browser , (struct sockaddr *)&server, sizeof(server)) != 0)
{
resourceError(err, "bind");
return 1;
}
if (err = listen(socket_browser , 3) != 0)
{
resourceError(err, "listen");
}
while (1){
c = sizeof(struct sockaddr_in);
server_socket= accept(socket_browser, (struct sockaddr *)&client, (socklen_t *)&c);
char buf[256];
int n;
n = recv(socket_newBrowser, buf, 256, 0);
if (n < 0){
resourceError(n,"recv");
}
int server_socket;
struct sockaddr_in server2;
server_socket= socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0)
{
resourceError(server_socket, "serverSocket");
}
server2.sin_addr.s_addr = inet_addr(ip);
server2.sin_family = AF_INET;
server2.sin_port = htons(80);
connect(server_socket, (struct sockaddr *)&server2, sizeof(server2))
send(server_socket, buf, strlen(buf), 0);
char reply[256];
int bytes_reply = 0;
do
{
bytes_reply = recv(server_socket, reply, sizeof(reply), 0);
// Need to check for double enter as this currently does not work in telnet
if (bytes_reply == -1)
{
perror("Recv error");
}
else
{
write(server_socket, reply, bytes_reply);
}
} while (bytes_reply > 0);
printf("connections closed");
}
return 0;
}
I think your problem (or at least a problem) is:
n = recv(socket_newBrowser, buf, 256, 0);
/*versus*/
send(server_socket, buf, strlen(buf), 0);
buf is not null-terminated, you should have used the n value returned from recv instead of strlen.
I've written a UDP send/receive function to send a struct and listen for another struct back. The bytes have to be sent in a particular order, but this is working OK as I'm using #pragma pack(1). The only problem that I'm having now is that if any Null values (0x00) appear in the struct, the rest of the data after the Null disappears.
I guess there's something fairly simple that I'm doing wrong, but here is my code:
typedef u_int8_t NN;
typedef u_int8_t X;
typedef int32_t S;
typedef u_int32_t U;
typedef char C;
typedef struct{
X test;
NN test2[2];
C test3[4];
S test4;
} Test;
int main(int argc, char** argv)
{
Test t;
memset( &t, 0, sizeof(t));
t.test = 0xde;
t.test2[0]=0xad; t.test2[1]=0x00;
t.test3[0]=0xbe; t.test3[1]=0xef; t.test3[2]=0xde; t.test3[3]=0xca;
t.test4=0xde;
LogOnResponse response;
udp_send_receive(&t, &response);
return 0;
}
And here is my send/receive function:
int send_and_receive(void* message, void* reply, int do_send, int expect_reply)
{
struct sockaddr_in serv_addr;
int sockfd, i, slen=sizeof(serv_addr);
int buflen = BUFLEN;
void* buf = NULL;
struct timeval tv;
int n_timeouts=1;
int recv_retval;
// printf("Message Size: %d\n", strlen(message));
if ( (strlen(message)) >= BUFLEN)
err("Message too big");
buf = malloc(buflen);
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
err("socket");
tv.tv_sec = timeout_seconds;
tv.tv_usec = timeout_microseconds;
if( setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0 ){
err("Setting Timout");
}
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if (inet_aton(IP_ADDRESS, &serv_addr.sin_addr)==0)
err("inet_aton() failed\n");
//---Timeout Send/Receive loop
do{
if(do_send == TRUE){
strcpy(buf, message);
if (sendto(sockfd, buf, buflen, 0, (struct sockaddr*)&serv_addr, slen)==-1)
err("sendto()");
}
if (expect_reply == TRUE){
if( (recv_retval = recvfrom(sockfd, buf, buflen, 0, (struct sockaddr*)&serv_addr, &slen)) == -1){
itercount++;
}
}
}while ((itercount < itermax) && (recv_retval == -1));
if ( itercount != itermax ){
memcpy(reply, buf, BUFLEN);
}
else{
reply=NULL;
}
close(sockfd);
free(buf);
return 0;
}
void udp_send_receive(void* message, void* reply)
{
send_and_receive(message, reply, TRUE, TRUE);
}
Running the above code and capturing the packets with WireShark shows:
Data: DEAD000000000000000000....
I'd like it to show:
Data: DEAD00BEEFDECADE
I'd really appreciate some pointers on this.
You can't use string functions (like strlen or strcpy) for binary data. It's because strings are terminated by the value zero (character '\0').
For example, you use strcpy to copy data, but it will stop as soon as is sees the string terminator meaning it will not copy all of the data.
Rather than using strcpy use
void * memcpy ( void * destination, const void * source, size_t num );
Doing strcpy(buf, message); in send_and_receive() is incorrect. I would update code to pass size of message and use that to copy memory as
udp_send_receive(&t, sizeof(t), &response);
void udp_send_receive(void* message, int len, void* reply){
send_and_receive(message, len reply, TRUE, TRUE);
}
int send_and_receive(void* message, int len, void* reply, int do_send, int expect_reply){
...
int buflen = len;
....
memcpy(buf, message, len); //instead of strcpt(buf, message)
...
}
I'm trying to make a server that can be connected to by multiple clients. Here's my code so far:
Client:
int main(int argc, char **argv) {
struct sockaddr_in servaddr;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) perror("Socket");
bzero((void *) &servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6782);
servaddr.sin_addr.s_addr = inet_addr(<server_ip_address>);
if (-1 == connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)))
perror("Connect");
while(1) {
char message[6];
fgets(message, 6, stdin);
message[5] = '\0';
send(sock, message, 6, 0);
}
close(sock);
}
Server:
int main(int argc, char **argv) {
fd_set fds, readfds;
int i, clientaddrlen;
int clientsock[2], rc, numsocks = 0, maxsocks = 2;
int serversock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serversock == -1) perror("Socket");
struct sockaddr_in serveraddr, clientaddr;
bzero(&serveraddr, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(6782);
if (-1 == bind(serversock, (struct sockaddr *)&serveraddr,
sizeof(struct sockaddr_in)))
perror("Bind");
if (-1 == listen(serversock, SOMAXCONN))
perror("Listen");
FD_ZERO(&fds);
FD_SET(serversock, &fds);
while(1) {
readfds = fds;
rc = select(FD_SETSIZE, &readfds, NULL, NULL, NULL);
if (rc == -1) {
perror("Select");
break;
}
for (i = 0; i < FD_SETSIZE; i++) {
if (FD_ISSET(i, &readfds)) {
if (i == serversock) {
if (numsocks < maxsocks) {
clientsock[numsocks] = accept(serversock,
(struct sockaddr *) &clientaddr,
(socklen_t *)&clientaddrlen);
if (clientsock[numsocks] == -1) perror("Accept");
FD_SET(clientsock[numsocks], &fds);
numsocks++;
} else {
printf("Ran out of socket space.\n");
}
} else {
int messageLength = 5;
char message[messageLength+1];
int in, index = 0, limit = messageLength+1;
while ((in = recv(clientsock[i], &message[index], limit, 0)) > 0) {
index += in;
limit -= in;
}
printf("%d\n", index);
printf("%s\n", message);
}
}
}
}
close(serversock);
return 0;
}
As soon as a client connects and sends its first message, the server just runs in an infinite loop, and spits out garbage from the message array. recv doesn't seem to receive anything. Can anyone see where i go wrong?
Two issues in your code:
You should do recv(i, ...) instead of recv(clientsock[i], ...)
After that you do not check if recv() failed, and therefore printf() prints out the uninitialised buffer message, hence the garbage in the output
You need to check for limit <= 0 in your read loop, before you call read.
In the while loop for the server, change the code to do recv(i) instead of recv(clientsocks[i]). I have implemented this code and it works with this change.
I replaced the else with the below and it works
} else {
/* int messageLength = 5;
char message[messageLength+1];
int in, index = 0, limit = messageLength+1;
memset ( &message[index] , 0, sizeof ( message [index] ) );
while ((in = recv(i, &message[index], limit, 0)) > 0) {
index += in;
limit -= in;
}
printf("%d\n", index);
printf("%s\n", message);
*/
bzero(buf, sizeof(buf));
if ((rval = read(i, buf, 1024)) < 0)
perror("reading stream message");
else if (rval == 0)
printf("Ending connection\n");
else
printf("-->%s\n", buf);
}
1) It is a good practice to use PF_INET(protocol family) rather than
AF_INET(address family) during the Socket creation .
2) within the while(1) loop
each time it is advisable to make your readfds empty by using FD_ZERO(&readfds).
in the recv() call you should use i rather than clientsocks[i]
you have to check return value of recv is negative(which indicating error in reading) if that is the case you do not have to print the message.
during printing the message make sure the stdout/server is ready for writing anything to it which you can do it by using writefds (3rd argument of select).