To generate RSA private key, 2048 bit. openssl genrsa -out privatekey.pem
To generate RSA public key openssl rsa -in privatekey.pem -pubout -out publickey.pem
chage private key to pkcs8 format: openssl pkcs8 -topk8 -inform PEM -in privatekey.pem -outform PEM -nocrypt
To create a hex-encoded message digest of a file: openssl dgst -md5 -hex file.txt
To sign a file using SHA-256 with binary file output: openssl dgst -sha256 -sign privatekey.pem -out signature.sign file.txt
To verify a signature: openssl dgst -sha256 -verify publickey.pem -signature signature.sign file.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "openssl/bio.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
#define IP "127.0.0.1"
#define PORT 8383
#define FILE_CACERT "cacert.pem"
#define FILE_PRIVATE_KEY "privatekey.pem"
int main()
{
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
SSL_CTX * ctx = SSL_CTX_new(SSLv23_server_method());
if(NULL == ctx) {
ERR_print_errors_fp(stdout);
exit(1);
}
if(SSL_CTX_use_certificate_file(ctx, FILE_CACERT, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stdout);
exit(1);
}
if(SSL_CTX_use_PrivateKey_file(ctx, FILE_PRIVATE_KEY, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stdout);
exit(1);
}
if(!SSL_CTX_check_private_key(ctx)) {
ERR_print_errors_fp(stdout);
exit(1);
}
int iSockFD = socket(AF_INET, SOCK_STREAM, 0);
if(iSockFD == -1) {
perror("socket");
exit(1);
}
struct sockaddr_in stServerAddr;
memset(&stServerAddr, 0, sizeof(stServerAddr));
stServerAddr.sin_family = AF_INET;
stServerAddr.sin_port = htons(PORT);
stServerAddr.sin_addr.s_addr = inet_addr(IP);
if(bind(iSockFD, (struct sockaddr*)&stServerAddr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
if(listen(iSockFD, 5) == -1) {
perror("listen");
exit(1);
}
while (1)
{
socklen_t iLen = sizeof(struct sockaddr);
struct sockaddr_in stClientAddr;
int iNewFD = accept(iSockFD, (struct sockaddr*)&stClientAddr, &iLen);
if(iNewFD == -1) {
perror("accept");
exit(1);
}
printf("%s:%d, socket %d\n",
inet_ntoa(stClientAddr.sin_addr),
ntohs(stClientAddr.sin_port),
iNewFD);
SSL * ssl = SSL_new(ctx);
SSL_set_fd(ssl, iNewFD);
if(SSL_accept(ssl) == -1) {
perror("SSL_accept");
close(iNewFD);
break;
}
char acBuf[BUFSIZ] = {0};
strcpy(acBuf, "server->client");
sleep(2);
iLen = SSL_write(ssl, acBuf, strlen(acBuf));
if(iLen <= 0) {
printf("SSL_write failed\n");
goto finish;
}
memset(acBuf, 0, sizeof(acBuf));
iLen = SSL_read(ssl, acBuf, sizeof(acBuf));
if(iLen <= 0) {
printf("SSL_read failed\n");
} else {
printf("SSL_read success, acBuf = %s\n", acBuf);
}
finish:
SSL_shutdown(ssl);
SSL_free(ssl);
close(iNewFD);
}
close(iSockFD);
SSL_CTX_free(ctx);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "openssl/bio.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
#define IP "127.0.0.1"
#define PORT 8383
void ShowCerts(SSL * ssl)
{
X509 * cert = SSL_get_peer_certificate(ssl);
if(NULL == cert) {
printf("no cert\n");
return ;
}
printf("cert information:\n");
char * line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("%s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("%s\n", line);
free(line);
X509_free(cert);
}
int main()
{
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
SSL_CTX * ctx = SSL_CTX_new(SSLv23_client_method());
if(NULL == ctx) {
ERR_print_errors_fp(stdout);
exit(1);
}
int iSockFD = socket(AF_INET, SOCK_STREAM, 0);
if(iSockFD <= 0) {
perror("socket");
exit(1);
}
struct sockaddr_in stServerAddr;
stServerAddr.sin_family = AF_INET;
stServerAddr.sin_port = htons(PORT);
if(inet_aton(IP, (struct in_addr*)&stServerAddr.sin_addr.s_addr) == 0) {
perror("inet_aton");
exit(1);
}
if(connect(iSockFD, (struct sockaddr*)&stServerAddr, sizeof(stServerAddr)) != 0) {
perror("connect");
exit(1);
}
SSL * ssl = SSL_new(ctx);
SSL_set_fd(ssl, iSockFD);
if(SSL_connect(ssl) == -1)
{
ERR_print_errors_fp(stderr);
}
else
{
ShowCerts(ssl);
}
char acBuf[BUFSIZ] = {0};
socklen_t iLen = SSL_read(ssl, acBuf, sizeof(acBuf));
if(iLen <= 0) {
printf("SSL_read failed\n");
goto finish;
} else {
printf("SSL_read success, acBuf = %s\n", acBuf);
}
memset(acBuf, 0, sizeof(acBuf));
strcpy(acBuf, "from client->server");
iLen = SSL_write(ssl, acBuf, strlen(acBuf));
if(iLen <= 0) {
printf("SSL_write failed\n");
} else {
printf("SSL_write success\n");
}
finish:
SSL_shutdown(ssl);
SSL_free(ssl);
close(iSockFD);
SSL_CTX_free(ctx);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include "openssl/bio.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
#define IP "127.0.0.1"
#define PORT 8383
#define TCP_TIMEOUT 2
static inline void itimeofday(long *sec, long *usec)
{
#if defined(__unix)
struct timeval time;
gettimeofday(&time, NULL);
if (sec) *sec = time.tv_sec;
if (usec) *usec = time.tv_usec;
#else
static long mode = 0, addsec = 0;
BOOL retval;
static unsigned long long freq = 1;
unsigned long long qpc;
if (mode == 0) {
retval = QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
freq = (freq == 0)? 1 : freq;
retval = QueryPerformanceCounter((LARGE_INTEGER*)&qpc);
addsec = (long)time(NULL);
addsec = addsec - (long)((qpc / freq) & 0x7fffffff);
mode = 1;
}
retval = QueryPerformanceCounter((LARGE_INTEGER*)&qpc);
retval = retval * 2;
if (sec) *sec = (long)(qpc / freq) + addsec;
if (usec) *usec = (long)((qpc % freq) * 1000000 / freq);
#endif
}
unsigned long long iclock64(void)
{
long s, u;
unsigned long long value;
itimeofday(&s, &u);
value = ((unsigned long long)s) * 1000 + (u / 1000);
return value;
}
unsigned int iclock()
{
return (unsigned int)(iclock64() & 0xfffffffful);
}
void vTcpSetNonBlock(int iSocket)
{
int opts;
opts = fcntl(iSocket, F_GETFL);
if(opts < 0) {
exit(1);
}
opts = (opts | O_NONBLOCK);
if(fcntl(iSocket, F_SETFL, opts) < 0) {
exit(1);
}
}
int iReadTimeout(
SSL * ssl,
int iSocket,
char * pcBuf,
int * piBufLen,
int iTimeout)
{
if(NULL == ssl || iSocket <= 0 || NULL == pcBuf || NULL == piBufLen) {
printf("iReadTimeout invlaid parameters\n");
return EXIT_FAILURE;
}
struct timeval stTimeInterval;
struct timeval stTimeIntervalTemp;
stTimeInterval.tv_sec = 0;
stTimeInterval.tv_usec = 10 * 1000;
int iOnce = 0;
int iError = 0;
unsigned int uiCurrentTime = iclock();
unsigned int uiEndTime;
if(iTimeout <= 0) uiEndTime = uiCurrentTime + 10 * 1000; //10 seconds
else uiEndTime = uiCurrentTime + iTimeout;
while ( (uiCurrentTime = iclock()) < uiEndTime )
{
stTimeIntervalTemp = stTimeInterval;
fd_set stReadSet;
FD_ZERO(&stReadSet);
FD_SET(iSocket, &stReadSet);
iOnce = select(iSocket+1, &stReadSet, NULL, NULL, &stTimeIntervalTemp);
if(1 == iOnce && FD_ISSET(iSocket, &stReadSet))
{
do {
iOnce = SSL_read(ssl, pcBuf, *piBufLen);
iError = SSL_get_error(ssl, iOnce);
switch(iError)
{
case SSL_ERROR_NONE:
{
return EXIT_SUCCESS;
}
break;
case SSL_ERROR_ZERO_RETURN:
{
//peer close the socket.
SSL_shutdown(ssl);
SSL_free(ssl);
close(iSocket);
return EXIT_FAILURE;
}
break;
case SSL_ERROR_WANT_READ:
{
//continue to read.
}
break;
default:
{
printf("SSL_read unknown error = %d\n", iError);
return EXIT_FAILURE;
}
break;
}
} while(SSL_pending(ssl) && (uiCurrentTime = iclock()) < uiEndTime );
}
else if(iOnce == 0)
{
continue;
}
return EXIT_FAILURE;
}
return TCP_TIMEOUT;
}
void ShowCerts(SSL * ssl)
{
X509 * cert = SSL_get_peer_certificate(ssl);
if(NULL == cert) {
printf("no cert\n");
return ;
}
printf("cert information:\n");
char * line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("%s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("%s\n", line);
free(line);
X509_free(cert);
}
int main()
{
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
SSL_CTX * ctx = SSL_CTX_new(SSLv23_client_method());
if(NULL == ctx) {
ERR_print_errors_fp(stdout);
exit(1);
}
int iSockFD = socket(AF_INET, SOCK_STREAM, 0);
if(iSockFD <= 0) {
perror("socket");
exit(1);
}
struct sockaddr_in stServerAddr;
stServerAddr.sin_family = AF_INET;
stServerAddr.sin_port = htons(PORT);
if(inet_aton(IP, (struct in_addr*)&stServerAddr.sin_addr.s_addr) == 0) {
perror("inet_aton");
exit(1);
}
if(connect(iSockFD, (struct sockaddr*)&stServerAddr, sizeof(stServerAddr)) != 0) {
perror("connect");
exit(1);
}
SSL * ssl = SSL_new(ctx);
SSL_set_fd(ssl, iSockFD);
if(SSL_connect(ssl) == -1)
{
ERR_print_errors_fp(stderr);
}
else
{
ShowCerts(ssl);
}
char acBuf[BUFSIZ] = {0};
socklen_t iLen = 0;
//socklen_t iLen = SSL_read(ssl, acBuf, sizeof(acBuf));
//if(iLen <= 0) {
// printf("SSL_read failed\n");
// goto finish;
//} else {
// printf("SSL_read success, acBuf = %s\n", acBuf);
//}
vTcpSetNonBlock(iSockFD);
int iBufLen = sizeof(acBuf);
int iRet = iReadTimeout(ssl, iSockFD, acBuf, &iBufLen, 1000);
if(iRet != EXIT_SUCCESS) {
printf("iReadTimeout failed, iRet = %d\n", iRet);
return -1;
}
printf("read success, acBuf = %s\n", acBuf);
memset(acBuf, 0, sizeof(acBuf));
strcpy(acBuf, "from client->server");
iLen = SSL_write(ssl, acBuf, strlen(acBuf));
if(iLen <= 0) {
printf("SSL_write failed\n");
} else {
printf("SSL_write success\n");
}
SSL_shutdown(ssl);
SSL_free(ssl);
close(iSockFD);
SSL_CTX_free(ctx);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "openssl/sha.h"
#include "openssl/crypto.h"
const char * str = "hello";
void printHash(unsigned char * md, int iLen)
{
for (int i = 0; i < iLen; i++)
{
printf("%02x", md[i]);
}
printf("\n");
}
void myHash1()
{
unsigned char md[SHA_DIGEST_LENGTH] = {0};
SHA1((unsigned char *)str, strlen(str), md);
printHash(md, SHA_DIGEST_LENGTH);
SHA_CTX c;
SHA1_Init(&c);
SHA1_Update(&c, str, strlen(str));
SHA1_Final(md, &c);
OPENSSL_cleanse(&c, sizeof(c));
printHash(md, SHA_DIGEST_LENGTH);
printf("\n");
}
void myHash224()
{
unsigned char md[SHA224_DIGEST_LENGTH] = {0};
SHA224((unsigned char *)str, strlen(str), md);
printHash(md, SHA224_DIGEST_LENGTH);
SHA256_CTX c;
SHA224_Init(&c);
SHA224_Update(&c, str, strlen(str));
SHA224_Final(md, &c);
OPENSSL_cleanse(&c, sizeof(c));
printHash(md, SHA224_DIGEST_LENGTH);
printf("\n");
}
void myHash256()
{
unsigned char md[SHA256_DIGEST_LENGTH] = {0};
SHA256((unsigned char *)str, strlen(str), md);
printHash(md, SHA256_DIGEST_LENGTH);
SHA256_CTX c;
SHA256_Init(&c);
SHA256_Update(&c, str, strlen(str));
SHA256_Final(md, &c);
OPENSSL_cleanse(&c, sizeof(c));
printHash(md, SHA256_DIGEST_LENGTH);
printf("\n");
}
void myHash384()
{
unsigned char md[SHA384_DIGEST_LENGTH] = {0};
SHA384((unsigned char *)str, strlen(str), md);
printHash(md, SHA384_DIGEST_LENGTH);
SHA512_CTX c;
SHA384_Init(&c);
SHA384_Update(&c, str, strlen(str));
SHA384_Final(md, &c);
OPENSSL_cleanse(&c, sizeof(c));
printHash(md, SHA384_DIGEST_LENGTH);
printf("\n");
}
void myHash512()
{
unsigned char md[SHA512_DIGEST_LENGTH] = {0};
SHA512((unsigned char *)str, strlen(str), md);
printHash(md, SHA512_DIGEST_LENGTH);
SHA512_CTX c;
SHA512_Init(&c);
SHA512_Update(&c, str, strlen(str));
SHA512_Final(md, &c);
OPENSSL_cleanse(&c, sizeof(c));
printHash(md, SHA512_DIGEST_LENGTH);
printf("\n");
}
int main()
{
myHash1();
myHash224();
myHash256();
myHash384();
myHash512();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "openssl/bio.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
#include "openssl/evp.h"
#include "openssl/buffer.h"
#include "openssl/md5.h"
//openssl dgst -md5 -hex Makefile
int main()
{
MD5_CTX ctx;
MD5_Init(&ctx);
FILE * file = fopen("Makefile", "rb");
if(NULL == file) {
return -1;
}
int iLen = 0;
unsigned char aucBuffer[1024] = {0};
while ( (iLen = fread(aucBuffer, 1, 1024, file)) > 0 )
{
MD5_Update(&ctx, aucBuffer, iLen);
}
unsigned char aucDigest[16] = {0};
MD5_Final(aucDigest, &ctx);
fclose(file);
char acMd5[33] = {0};
for (int i = 0; i < 16; i++)
{
char acTemp[3] = {0};
sprintf(acTemp, "%02x", aucDigest[i]);
strcat(acMd5, acTemp);
}
printf("acMd5 = %s\n", acMd5);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "openssl/bio.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
#include "openssl/evp.h"
#include "openssl/buffer.h"
int main()
{
char acInput[BUFSIZ] = {0};
char acOutput[BUFSIZ] = {0};
char acDecOut[BUFSIZ] = {0};
strcpy(acInput, "hello");
EVP_EncodeBlock((unsigned char*)acOutput, (const unsigned char*)acInput, strlen(acInput));
EVP_DecodeBlock((unsigned char*)acDecOut, (const unsigned char*)acOutput, strlen(acOutput));
printf("acInput = %s\n", acInput);
printf("acOutput = %s\n", acOutput);
printf("acDecOut = %s\n", acDecOut);
return 0;
}
#ifndef TCP_UNIT_WIN_HJ
#define TCP_UNIT_WIN_HJ
#ifdef WIN32
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <MSTcpIP.h>
#include <iphlpapi.h>
#else
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/epoll.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <net/if.h>
#include <features.h>
#include <fcntl.h>
#endif
#include "common_def.h"
#include "utility.h"
/*
* @return
* EXIT_SUCCESS: success.
* EXIT_FAILURE: failed.
* TCP_TIMEOUT: read or write timeout.
* TCP_EOF: peer close the connection.
*/
void tcp_SetNonblock(int iSocket);
void tcp_Setblock(int iSocket);
void tcp_vCloseSocket(int & riSocket);
/*
* @param piSocket[out]: if success, return socket descriptor.
* @param pcAddr[in]: ip address.
* @param usPort[in]: ip port.
* @param iTimeout[in]: Millisecond.
*/
int tcp_iConnect(int * piSocket, const char * pcAddr, unsigned short usPort, int iTimeout);
/*
* @param iSocket[in]: socket descriptor.
* @param pcBuf[out]: buffer used to recv data.
* @param piBufLen[in|out]: input the length of pcBuf, output the recvd length.
*/
int tcp_iRecvMsg(int iSocket, char * pcBuf, int * piBufLen);
/*
* @param iSocket[in]: socket descriptor.
* @param pcBuf[out]: buffer used to recv data.
* @param piBufLen[in|out]:
* input the size of data want to read.
* if return EXIT_SUCCESS, it means read success,
* if return TCP_TIMEOUT, piBufLen output the size had already read.
* @param iTimeout[in]: Millisecond.
*/
int tcp_iRecvMsgTimeout(int iSocket, char * pcBuf, int * piBufLen, int iTimeout);
/*
* @param iSocket[in]: socket descriptor.
* @param pcBuf[in]:
* @param piBufLen[in|out]: input the size of data ready to send, output the really size of data send success.
*/
int tcp_iSendMsg(int iSocket, const char * pcBuf, int * piBufLen);
/*
* @param iSocket[in]: socket descriptor.
* @param pcBuf[in]:
* @param iBufLen[in]: the size of data ready to send.
*/
int tcp_iSendAllMsg(int iSocket, const char * pcBuf, int iBufLen);
/*
* @param iSocket[in]: socket descriptor.
* @param pcBuf[in]:
* @param iSize[in]: the size of data ready to send.
* @param iTimeout[in]: Millisecond. if your input <=0, it default use 100 milliseconds.
*/
int tcp_iSendMsgTimeout(int iSocket, const char * pcBuf, int iSize, int iTimeout);
#endif
```cpp #include “tcpunit.h” #ifdef WIN32
void tcp_SetNonblock(int iSocket) { unsigned long flags = 1; ioctlsocket(iSocket, FIONBIO, &flags); }
void tcp_Setblock(int iSocket) { unsigned long flags = 0; ioctlsocket(iSocket, FIONBIO, &flags); }
void tcp_vCloseSocket(int & riSocket) { if(riSocket != 0) { closesocket(riSocket); riSocket = 0; } }
int tcp_iConnect(int *piSocket, const char * pcAddr, unsigned short usPort, int iTimeout) { int iRet;
if(NULL == piSocket || NULL == pcAddr || 0 == usPort) {
printf("tcp_iConnect input error!\n");
return EXIT_FAILURE;
}
int iSocket = socket(AF_INET, SOCK_STREAM, 0);
if(iSocket < 0) {
printf("tcp_iConnect socket error!\n");
return EXIT_FAILURE;
}
int iTime = 2;
setsockopt(iSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&iTime, sizeof(int));
int iKeepAlive = 1; //开启keepalive属性
int iKeepIdle = 120; //如果连接在120秒内没有任何数据往来,则进行探测
int iKeepInterval = 5; //探测发包的时间间隔为5秒
//int iKeepCount = 3; //探测尝试的次数
iRet = setsockopt(iSocket, SOL_SOCKET, SO_KEEPALIVE, (char*)&iKeepAlive, sizeof(iKeepAlive));
if(iRet != 0) {
printf("tcp_iConnect SO_KEEPALIVE error=%d\n", WSAGetLastError());
}
DWORD iByteNum;
tcp_keepalive sPara = {1, iKeepIdle*1000, iKeepInterval*1000};
iRet = WSAIoctl(iSocket, SIO_KEEPALIVE_VALS, &sPara, sizeof(sPara), &sPara, sizeof(sPara), &iByteNum,NULL,NULL);
if(iRet != 0) {
printf("tcp_iConnect WSAIoctl SIO_KEEPALIVE_VALS error=%d\n", WSAGetLastError());
}
tcp_SetNonblock(iSocket);
struct sockaddr_in stAddr;
memset(&stAddr, 0, sizeof(stAddr));
stAddr.sin_family = AF_INET;
stAddr.sin_port = htons(usPort);
stAddr.sin_addr.s_addr = inet_addr(pcAddr);
memset(stAddr.sin_zero, 0x00, 8);
iRet = ::connect(iSocket, (struct sockaddr*)&stAddr, sizeof(stAddr));
if(iRet < 0)
{
DWORD dwError = GetLastError();
if(dwError != WSAEINPROGRESS && dwError != WSAEWOULDBLOCK) {
printf("tcp_iConnect connect error(%d)\n", GetLastError());
tcp_vCloseSocket(iSocket);
return EXIT_FAILURE;
}
}
else if(iRet == 0)
{
tcp_Setblock(iSocket);
return EXIT_SUCCESS;
}
fd_set stReadSet;
fd_set stWriteSet;
FD_ZERO(&stReadSet);
FD_SET(iSocket, &stReadSet);
stWriteSet = stReadSet;
struct timeval stTimeInterval;
stTimeInterval.tv_sec = iTimeout / 1000;
stTimeInterval.tv_usec = (iTimeout % 1000) * 1000;
iRet = select(0, &stReadSet , &stWriteSet, NULL, &stTimeInterval);
if(iRet <= 0)
{
printf("tcp_iConnect select iRet=%d\n", iRet);
tcp_vCloseSocket(iSocket);
return EXIT_FAILURE;
}
DONE: tcp_Setblock(iSocket);
*piSocket = iSocket;
return EXIT_SUCCESS; }
int tcp_iRecvMsg(int iSocket, char pcBuf, int * piBufLen) { if(iSocket <=0 || NULL == pcBuf || NULL == piBufLen || (piBufLen < 0)) { printf(“tcp_iRecvMsg input error!\n”); return EXIT_FAILURE; }
struct timeval stTimeInterval;
stTimeInterval.tv_sec = 0;
stTimeInterval.tv_usec = 100 * 1000;
fd_set stReadSet;
FD_ZERO(&stReadSet);
FD_SET(iSocket, &stReadSet);
int iActiveNum = select(iSocket + 1, &stReadSet, NULL, NULL, &stTimeInterval);
if(iActiveNum == 1 && FD_ISSET(iSocket, &stReadSet))
{
int iRecv = recv(iSocket, pcBuf , *piBufLen, 0);
if(iRecv > 0)
{
*piBufLen = iRecv;
return EXIT_SUCCESS;
}
else if(iRecv == 0)
{
return TCP_EOF;
}
}
else if(iActiveNum == 0)
{
return TCP_TIMEOUT;
}
return EXIT_FAILURE; }
int tcp_iRecvMsgTimeout(int iSocket, char * pcBuf, int * piBufLen, int iTimeout) { if(iSocket <=0 || NULL == pcBuf || NULL == piBufLen || (*piBufLen <= 0)) { printf(“tcp_iRecvMsgTimeout input error!\n”); return EXIT_FAILURE; }
struct timeval stTimeInterval;
struct timeval stTimeIntervalTemp;
stTimeInterval.tv_sec = 0;
stTimeInterval.tv_usec = 10 * 1000;
int iOnce = 0;
int iRecv = 0;
char *pcIndex = pcBuf;
unsigned int uiCurrentTime = iclock();
unsigned int uiEndTime;
if(iTimeout <= 0) uiEndTime = uiCurrentTime + 10 * 1000;
else uiEndTime = uiCurrentTime + iTimeout * 1000;
while ( (uiCurrentTime = iclock()) < uiEndTime )
{
stTimeIntervalTemp = stTimeInterval;
fd_set stReadSet;
FD_ZERO(&stReadSet);
FD_SET(iSocket, &stReadSet);
iOnce = select(iSocket + 1, &stReadSet , NULL, NULL, &stTimeIntervalTemp);
if(1 == iOnce && FD_ISSET(iSocket, &stReadSet))
{
iOnce = recv(iSocket, pcIndex , *piBufLen - iRecv, 0);
if(iOnce > 0)
{
iRecv += iOnce;
if(iRecv >= *piBufLen)
{
return EXIT_SUCCESS;
}
else
{
pcIndex += iOnce;
continue;
}
}
else if(iOnce == 0)
{
return TCP_EOF;
}
}
else if(iOnce == 0)
{
continue;
}
return EXIT_FAILURE;
}
*piBufLen = iRecv;
return TCP_TIMEOUT; }
int tcp_iSendMsg(int iSocket, const char pcBuf, int * piBufLen) { if(iSocket <= 0 || NULL == pcBuf || NULL == piBufLen || (piBufLen <= 0)) { printf(“tcp_iSendMsg input error!\n”); return EXIT_FAILURE; }
int iSendLen = send(iSocket, pcBuf, *piBufLen, 0);
if(iSendLen < 0) {
printf("tcp_iSendMsg send error. return value = %d. \n",iSendLen);
return EXIT_FAILURE;
}
*piBufLen = iSendLen;
return EXIT_SUCCESS; }
int tcp_iSendAllMsg(int iSocket, const char *pcBuf, int iBufLen) { if(iSocket <= 0 || NULL == pcBuf || 0 == iBufLen) { printf(“tcp_iSendAllMsg input error!\n”); return EXIT_FAILURE; }
int iSendLen = 0;
while(iSendLen < iBufLen)
{
int iSendLenTmp = send(iSocket, pcBuf + iSendLen, iBufLen - iSendLen, 0);
if(iSendLenTmp < 0) {
printf("tcp_iSendAllMsg send error. return value = %d. \n",iSendLenTmp);
return EXIT_FAILURE;
}
iSendLen += iSendLenTmp;
}
return EXIT_SUCCESS; }
int tcp_iSendMsgTimeout(int iSocket, const char *pcBuf, int iSize, int iTimeout) { if(iSocket <= 0 || NULL == pcBuf || iSize <= 0) { printf(“tcp_iSendMsgTimeout input error!\n”); return EXIT_FAILURE; }
int iTotalWriteLen = 0;
char * pcBufferIndex = (char *)pcBuf;
unsigned int uiCurrentTime = iclock();
unsigned int uiEndTime;
if(iTimeout <= 0) uiEndTime = uiCurrentTime + 100 * 1000;
else uiEndTime = uiCurrentTime + iTimeout * 1000;
while((uiCurrentTime = iclock()) < uiEndTime)
{
struct timeval stTimeInterval;
stTimeInterval.tv_sec = 0;
stTimeInterval.tv_usec = 10 * 1000;
fd_set stWriteSet;
FD_ZERO(&stWriteSet);
FD_SET(iSocket, &stWriteSet);
int iOnce = select(iSocket + 1, NULL , &stWriteSet, NULL, &stTimeInterval);
if(1 == iOnce && FD_ISSET(iSocket, &stWriteSet))
{
int iWriteLen = send(iSocket, pcBufferIndex, iSize - iTotalWriteLen, 0);
if(iWriteLen > 0)
{
iTotalWriteLen += iWriteLen;
if(iTotalWriteLen >= iSize)
{
/** write completely */
return EXIT_SUCCESS;
}
else
{
pcBufferIndex += iWriteLen;
continue;
}
}
else
{
printf("tcp_iSendMsgTimeout send error\n");
return EXIT_FAILURE;
}
}
else if(0 == iOnce)
{
continue; // select timeout
}
else
{
printf("tcp_iSendMsgTimeout select error\n");
return EXIT_FAILURE;
}
}
return TCP_TIMEOUT; }