#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// To convert a-f or A-F to a decimal number
int chartoint(int c)
{
char hex[] = "aAbBcCdDeEfF";
int i;
int result = 0;
for(i = 0; result == 0 && hex[i] != '\0'; i++)
{
if(hex[i] == c)
{
result = 10 + (i / 2);
}
}
return result;
}
unsigned int htoi(const char s[])
{
unsigned int result = 0;
int i = 0;
int proper = 1;
int temp;
//To take care of 0x and 0X added before the hex no.
if(s[i] == '0')
{
++i;
if(s[i] == 'x' || s[i] == 'X')
{
++i;
}
}
while(proper && s[i] != '\0')
{
result = result * 16;
if(s[i] >= '0' && s[i] <= '9')
{
result = result + (s[i] - '0');
}
else
{
temp = chartoint(s[i]);
if(temp == 0)
{
proper = 0;
}
else
{
result = result + temp;
}
}
++i;
}
//If any character is not a proper hex no. , return 0
if(!proper)
{
result = 0;
}
return result;
}
int main(void)
{
char *endp = NULL;
char test[20];
printf("\nEnter a hexadecimal pattern : ");
scanf("%s",test);
if(htoi(test) == 0)
{
printf("\nEntered characters not proper Hexadecimal Number!!!\n");
exit(0);
}
printf("Hex : %s\tDecimal: %d\n" ,test, htoi(test));
}
Master programming effortlessly with Simplest Codings. From core algorithms and LLMs to clean code in Java, C++, and Python—get clear, bite-sized tutorials and practical developer guides for all skill levels.
Sunday, August 22, 2010
Hexadecimal to Integer Conversion in C
A simple implementation of converter which converts hexadecimal string to an integer.
Thursday, August 19, 2010
IPC Shared Memory Implementation in C
A simple Implementation of Shared Memory in C
Shared Memory is a type of IPC where the two processes share same memory chunk and use it for IPC. One process writes into that memory and other reads it.
After running the Server you can see the attached Shared Memory
After running the client the memory is freed.
Shared Memory is a type of IPC where the two processes share same memory chunk and use it for IPC. One process writes into that memory and other reads it.
After running the Server you can see the attached Shared Memory
vgupta80@linux unixprog> ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x0000162e 65537 vgupta80 666 27 1
After running the client the memory is freed.
------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x0000162e 65537 vgupta80 666 27 0
//SHMServer.C
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 27
void die(char *s)
{
perror(s);
exit(1);
}
int main()
{
char c;
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)
die("shmget");
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
die("shmat");
/*
* * Put some things into the memory for the
* other process to read.
* */
s = shm;
for (c = 'a'; c <= 'z'; c++)
*s++ = c;
/*
* Wait until the other process
* changes the first character of our memory
* to '*', indicating that it has read what
* we put there.
*/
while (*shm != '*')
sleep(1);
exit(0);
}
//SHMClient.C
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 27
void die(char *s)
{
perror(s);
exit(1);
}
int main()
{
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)
die("shmget");
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
die("shmat");
//Now read what the server put in the memory.
for (s = shm; *s != '\0'; s++)
putchar(*s);
putchar('\n');
/*
*Change the first character of the
*segment to '*', indicating we have read
*the segment.
*/
*shm = '*';
exit(0);
}
IPC Message Queue Implementation in C
A simple implementation of IPC Message Queues.
IPC_msgq_send.c adds the message on the message queue .
IPC_msgq_rcv.c removes the message from the message queue.
To use this program first compile and run IPC_msgq_send.c to add a message to the message queue. To see the Message Queue type ipcs -q on your Unix/Linux Terminal.
Now compile and run IPC_msgq_rcv.c to read the message from the Message Queue.
To see that you have read the message again use ipcs -q
IPC_msgq_send.c adds the message on the message queue .
IPC_msgq_rcv.c removes the message from the message queue.
To use this program first compile and run IPC_msgq_send.c to add a message to the message queue. To see the Message Queue type ipcs -q on your Unix/Linux Terminal.
Now compile and run IPC_msgq_rcv.c to read the message from the Message Queue.
To see that you have read the message again use ipcs -q
//IPC_msgq_send.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 128
void die(char *s)
{
perror(s);
exit(1);
}
typedef struct msgbuf
{
long mtype;
char mtext[MAXSIZE];
};
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
size_t buflen;
key = 1234;
if ((msqid = msgget(key, msgflg )) < 0) //Get the message queue ID for the given key
die("msgget");
//Message Type
sbuf.mtype = 1;
printf("Enter a message to add to message queue : ");
scanf("%[^\n]",sbuf.mtext);
getchar();
buflen = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
{
printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
die("msgsnd");
}
else
printf("Message Sent\n");
exit(0);
}
//IPC_msgq_rcv.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 128
void die(char *s)
{
perror(s);
exit(1);
}
typedef struct msgbuf
{
long mtype;
char mtext[MAXSIZE];
} ;
main()
{
int msqid;
key_t key;
struct msgbuf rcvbuffer;
key = 1234;
if ((msqid = msgget(key, 0666)) < 0)
die("msgget()");
//Receive an answer of message type 1.
if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
die("msgrcv");
printf("%s\n", rcvbuffer.mtext);
exit(0);
}
SCTP Server Client Implementation in C
Here's a simple implementation of SCTP server and client in C
This is how the connection is established :
The Client initiates the connection with an INIT packet . Server replies back by sending the INIT-ACK.
This packet also contains a unique context which identifies this connection. This context is called as COOKIE. The client then responds with a COOKIE-ECHO with the cookie sent by the server.
Now the server allocates the necessary resources required by the connection and replies back to the client with COOKIE-ACK.
And this is how the connection is terminated.
This is a detailed connection diagram for this program is as follows
Note: To compile this code, sctp dev libraries are needed .
For ubuntu : sudo apt-get install libsctp-dev
This is how the connection is established :
This packet also contains a unique context which identifies this connection. This context is called as COOKIE. The client then responds with a COOKIE-ECHO with the cookie sent by the server.
Now the server allocates the necessary resources required by the connection and replies back to the client with COOKIE-ACK.
And this is how the connection is terminated.
This is a detailed connection diagram for this program is as follows
//SCTPServer.C To compile - gcc sctpserver.c - o server - lsctp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#define MAX_BUFFER 1024
#define MY_PORT_NUM 62324 /* This can be changed to suit the need and should be same in server and client */
int
main ()
{
int listenSock, connSock, ret, in, flags, i;
struct sockaddr_in servaddr;
struct sctp_initmsg initmsg;
struct sctp_event_subscribe events;
struct sctp_sndrcvinfo sndrcvinfo;
char buffer[MAX_BUFFER + 1];
listenSock = socket (AF_INET, SOCK_STREAM, IPPROTO_SCTP);
if(listenSock == -1)
{
printf("Failed to create socket\n");
perror("socket()");
exit(1);
}
bzero ((void *) &servaddr, sizeof (servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl (INADDR_ANY);
servaddr.sin_port = htons (MY_PORT_NUM);
ret = bind (listenSock, (struct sockaddr *) &servaddr, sizeof (servaddr));
if(ret == -1 )
{
printf("Bind failed \n");
perror("bind()");
close(listenSock);
exit(1);
}
/* Specify that a maximum of 5 streams will be available per socket */
memset (&initmsg, 0, sizeof (initmsg));
initmsg.sinit_num_ostreams = 5;
initmsg.sinit_max_instreams = 5;
initmsg.sinit_max_attempts = 4;
ret = setsockopt (listenSock, IPPROTO_SCTP, SCTP_INITMSG,
&initmsg, sizeof (initmsg));
if(ret == -1 )
{
printf("setsockopt() failed \n");
perror("setsockopt()");
close(listenSock);
exit(1);
}
ret = listen (listenSock, 5);
if(ret == -1 )
{
printf("listen() failed \n");
perror("listen()");
close(listenSock);
exit(1);
}
while (1)
{
char buffer[MAX_BUFFER + 1];
int len;
//Clear the buffer
bzero (buffer, MAX_BUFFER + 1);
printf ("Awaiting a new connection\n");
connSock = accept (listenSock, (struct sockaddr *) NULL, (int *) NULL);
if (connSock == -1)
{
printf("accept() failed\n");
perror("accept()");
close(connSock);
continue;
}
else
printf ("New client connected....\n");
in = sctp_recvmsg (connSock, buffer, sizeof (buffer),
(struct sockaddr *) NULL, 0, &sndrcvinfo, &flags);
if( in == -1)
{
printf("Error in sctp_recvmsg\n");
perror("sctp_recvmsg()");
close(connSock);
continue;
}
else
{
//Add '\0' in case of text data
buffer[in] = '\0';
printf (" Length of Data received: %d\n", in);
printf (" Data : %s\n", (char *) buffer);
}
close (connSock);
}
return 0;
}
//SCTPClient.C
// To compile - gcc sctpclt.c -o client -lsctp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
#define MAX_BUFFER 1024
#define MY_PORT_NUM 62324 /* This can be changed to suit the need and should be same in server and client */
int
main (int argc, char* argv[])
{
int connSock, in, i, ret, flags;
struct sockaddr_in servaddr;
struct sctp_status status;
char buffer[MAX_BUFFER + 1];
int datalen = 0;
/*Get the input from user*/
printf("Enter data to send: ");
fgets(buffer, MAX_BUFFER, stdin);
/* Clear the newline or carriage return from the end*/
buffer[strcspn(buffer, "\r\n")] = 0;
/* Sample input */
//strncpy (buffer, "Hello Server", 12);
//buffer[12] = '\0';
datalen = strlen(buffer);
connSock = socket (AF_INET, SOCK_STREAM, IPPROTO_SCTP);
if (connSock == -1)
{
printf("Socket creation failed\n");
perror("socket()");
exit(1);
}
bzero ((void *) &servaddr, sizeof (servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons (MY_PORT_NUM);
servaddr.sin_addr.s_addr = inet_addr ("127.0.0.1");
ret = connect (connSock, (struct sockaddr *) &servaddr, sizeof (servaddr));
if (ret == -1)
{
printf("Connection failed\n");
perror("connect()");
close(connSock);
exit(1);
}
ret = sctp_sendmsg (connSock, (void *) buffer, (size_t) datalen,
NULL, 0, 0, 0, 0, 0, 0);
if(ret == -1 )
{
printf("Error in sctp_sendmsg\n");
perror("sctp_sendmsg()");
}
else
printf("Successfully sent %d bytes data to server\n", ret);
close (connSock);
return 0;
}
Note: To compile this code, sctp dev libraries are needed .
For ubuntu : sudo apt-get install libsctp-dev
Monday, August 16, 2010
Secure Server Client using OpenSSL in C
Overview of the SSL handshake
Steps involved in SSL handshake(Courtesy:http://www.pierobon.org):
- The client sends the server the client's SSL version number, cipher settings, randomly generated data, and other information the server needs to communicate with the client using SSL.
- The server sends the client the server's SSL version number, cipher settings, randomly generated data, and other information the client needs to communicate with the server over SSL. The server also sends its own digital certificate and, if the client is requesting a server resource that requires client authentication, requests the client's digital certificate.
- The client uses the information sent by the server to authenticate the server. If the server cannot be authenticated, the user is warned of the problem that an encrypted and authenticated connection cannot be established. If the server can be successfully authenticated, the client proceeds.
- Using all data generated in the handshake so far, the client creates the premaster secret for the session, encrypts it with the server's public key (obtained from the server's digital certificate), and sends the encrypted premaster secret to the server.
- If the server has requested client authentication (an optional step in the handshake), the client also signs another piece of data that is unique to this handshake and known by both the client and server. In this case the client sends both the signed data and the client's own digital certificate to the server along with the encrypted premaster secret.
- If the server has requested client authentication, the server attempts to authenticate the client. If the client cannot be authenticated, the session is terminated. If the client can be successfully authenticated, the server uses its private key to decrypt the premaster secret, then performs a series of steps which the client also performs, starting from the same premaster secret to generate the master secret.
- Both the client and the server use the master secret to generate session keys which are symmetric keys used to encrypt and decrypt information exchanged during the SSL session and to verify its integrity.
- The client informs the server that future messages from the client will be encrypted with the session key. It then sends a separate encrypted message indicating that the client portion of the handshake is finished.
- The server sends a message to the client informing it that future messages from the server will be encrypted with the session key. It then sends a separate encrypted message indicating that the server portion of the handshake is finished.
- The SSL handshake is now complete, and the SSL session has begun. The client and the server use the session keys to encrypt and decrypt the data they send to each other and to validate its integrity.
Here's an implementation of Secure Server Client using openssl.
It is a piece of code taken from http://www.cs.utah.edu/~swalton/listings/sockets/programs
Of course you need to have OpenSSL installed in your system first. You can download latest OpenSSL package at OpenSSL Source
Before running this program you will need a Certificate which is used in this program. You can generate your own certificate using this command
openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem
, where mycert.pem is the name of the Certificate file.
To run the Server
Compile : gcc -Wall -o ssl-server SSL-Server.c -L/usr/lib -lssl -lcrypto
Run : sudo ./ssl-server <portnum>
To run the Client
Compile : gcc -Wall -o ssl-client SSL-Client.c -L/usr/lib -lssl -lcrypto
Run : ./ssl-client <hostname> <portnum>
//SSL-Server.c
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <resolv.h>
#include "openssl/ssl.h"
#include "openssl/err.h"
#define FAIL -1
int OpenListener(int port)
{ int sd;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
perror("can't bind port");
abort();
}
if ( listen(sd, 10) != 0 )
{
perror("Can't configure listening port");
abort();
}
return sd;
}
int isRoot()
{
if (getuid() != 0)
{
return 0;
}
else
{
return 1;
}
}
SSL_CTX* InitServerCTX(void)
{ SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
SSL_load_error_strings(); /* load all error messages */
method = TLSv1_2_server_method(); /* create new server-method instance */
ctx = SSL_CTX_new(method); /* create new context from method */
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile)
{
/* set the local certificate from CertFile */
if ( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* set the private key from KeyFile (may be the same as CertFile) */
if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* verify private key */
if ( !SSL_CTX_check_private_key(ctx) )
{
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
}
void ShowCerts(SSL* ssl)
{ X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
X509_free(cert);
}
else
printf("No certificates.\n");
}
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{ char buf[1024];
char reply[1024];
int sd, bytes;
const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
else
{
ShowCerts(ssl); /* get any certificates */
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
if ( bytes > 0 )
{
buf[bytes] = 0;
printf("Client msg: \"%s\"\n", buf);
sprintf(reply, HTMLecho, buf); /* construct reply */
SSL_write(ssl, reply, strlen(reply)); /* send reply */
}
else
ERR_print_errors_fp(stderr);
}
sd = SSL_get_fd(ssl); /* get socket connection */
SSL_free(ssl); /* release SSL state */
close(sd); /* close connection */
}
int main(int count, char *strings[])
{ SSL_CTX *ctx;
int server;
char *portnum;
if(!isRoot())
{
printf("This program must be run as root/sudo user!!");
exit(0);
}
if ( count != 2 )
{
printf("Usage: %s <portnum>\n", strings[0]);
exit(0);
}
SSL_library_init();
portnum = strings[1];
ctx = InitServerCTX(); /* initialize SSL */
LoadCertificates(ctx, "mycert.pem", "mycert.pem"); /* load certs */
server = OpenListener(atoi(portnum)); /* create server socket */
while (1)
{ struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SSL *ssl;
int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
ssl = SSL_new(ctx); /* get new SSL state with context */
SSL_set_fd(ssl, client); /* set connection socket to SSL state */
Servlet(ssl); /* service connection */
}
close(server); /* close server socket */
SSL_CTX_free(ctx); /* release context */
}
//SSL-Client.c
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define FAIL -1
int OpenConnection(const char *hostname, int port)
{ int sd;
struct hostent *host;
struct sockaddr_in addr;
if ( (host = gethostbyname(hostname)) == NULL )
{
perror(hostname);
abort();
}
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if ( connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
close(sd);
perror(hostname);
abort();
}
return sd;
}
SSL_CTX* InitCTX(void)
{ SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms(); /* Load cryptos, et.al. */
SSL_load_error_strings(); /* Bring in and register error messages */
method = TLSv1_2_client_method(); /* Create new client-method instance */
ctx = SSL_CTX_new(method); /* Create new context */
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void ShowCerts(SSL* ssl)
{ X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line); /* free the malloc'ed string */
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line); /* free the malloc'ed string */
X509_free(cert); /* free the malloc'ed certificate copy */
}
else
printf("Info: No client certificates configured.\n");
}
int main(int count, char *strings[])
{ SSL_CTX *ctx;
int server;
SSL *ssl;
char buf[1024];
int bytes;
char *hostname, *portnum;
if ( count != 3 )
{
printf("usage: %s <hostname> <portnum>\n", strings[0]);
exit(0);
}
SSL_library_init();
hostname=strings[1];
portnum=strings[2];
ctx = InitCTX();
server = OpenConnection(hostname, atoi(portnum));
ssl = SSL_new(ctx); /* create new SSL connection state */
SSL_set_fd(ssl, server); /* attach the socket descriptor */
if ( SSL_connect(ssl) == FAIL ) /* perform the connection */
ERR_print_errors_fp(stderr);
else
{ char *msg = "Hello???";
printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
ShowCerts(ssl); /* get any certs */
SSL_write(ssl, msg, strlen(msg)); /* encrypt & send message */
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */
buf[bytes] = 0;
printf("Received: \"%s\"\n", buf);
SSL_free(ssl); /* release connection state */
}
close(server); /* close socket */
SSL_CTX_free(ctx); /* release context */
return 0;
}
Update: The code is updated to use more secure TLS v1.2 methods . To compile and use this code, please make sure you have latest OpenSSL which support TLS v1.2Custom strncat function in C
This is a simple implementation of Variable length String Concatenation function.
It'll concatenate the mentioned length of a string into another string.
It'll concatenate the mentioned length of a string into another string.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *my_strncat(char *target1,const char *source1,int no);
int main()
{
char *source;
char *target;
char *ret;
int no_of_char;
source=(char*)malloc(10);
target=(char*)malloc(20);
printf("enter the string :\n");
scanf("%s",target);
printf("enter the string to be concatenated:\n");
scanf("%s",source);
printf("\nenter the number of characters to be concatenated:");
scanf("%d",&no_of_char);
ret=my_strncat(target,source,no_of_char);
printf("\nThe copied string is %s \n", ret);
free(source);
free(target);
return EXIT_SUCCESS;
}
char * my_strncat(char *target1,const char *source1,int no)
{
char *tempt=target1;
int n=0;
while(*target1)
{
target1++;
}
target1--;
if(*target1!='\n')
{
target1++;
}
while(n<no)
{
*target1=*source1;
target1++;
source1++;
n++;
}
*target1='\0';
return tempt;
}
Custom strncpy function in C
Here's a simple implementation of a custom desired length string copy function. This function copies a string into another upto a desired length.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *source;
char *target;
char *ret;
int no_of_char;
/*function prototype it takes string and returns address*/
char *my_strncpy(char *target1,const char *source1,int no);
source=(char*)malloc(20);
target=(char*)malloc(20);
printf("enter the string to be copied:\n");
fgets(source,20,stdin); //taking input from user
printf("\nenter the number of characters to be copied:");
scanf("%d",&no_of_char);
ret=my_strncpy(target,source,no_of_char);
printf("\nThe address of copy of string is %d ",ret ); //print the address of copt of string
printf("\nThe copied string is %s \n", ret); //print the copy of string
free(source);
free(target);
return EXIT_SUCCESS;
}
char * my_strncpy(char *target1,const char *source1,int no)
{
char *tempt=target1;
int n=0;
while(n<no)
{
*target1=*source1;
target1++;
source1++;
n++;
}
*target1='\0';
return tempt;
}
Subscribe to:
Posts (Atom)
-
Overview of the SSL handshake Courtesy: http://www-01.ibm.com/support/knowledgecenter Steps involved in SSL handshake (Courtesy:...
-
To implement the kind of storage which stores strings as the search keys , there is a need to have special data structures which can store ...
-
A simple implementation of a packet sniffer in C on linux platform using the libpcap library. This packet sniffer currently sniffs IP , TCP ...


