title: A simple TCP server

text:
# Question
Title: A simple TCP server
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.

Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N. When someone connects to that port, the program calculates sum of its IP address fields and sends it back to the client with trailing newline and closes connection.

* Port number N is a valid port, and 210 \< N \< 215
* Trailing newline can be either `\n`or `\r\n`
* You can use either IPv4 or IPv6. Since IPv6 addresses are written in hexadecimal form, you must also provide result in same format, for example `2001:0db8:0000:0042:0000:8a2e:0370:7334 => 12ecd`.

This is . Standard rules and loopholes apply.

## Example

You run your server with `./server 1234`. The server is now running and waiting for connections on port 1234. Then a client from `127.0.0.1` connects to your server. Your server performs a simple calculation: `127+0+0+1 => 128` and sends the result to the client (with trailing newline): `128\n`. Then server closes connection and waits for next client.

## Leaderboard

```
var QUESTION_ID=76379,OVERRIDE_USER=20569;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Bash + netcat + ss + …, ~~65~~ 60 characters

```
nc -lp$1 -c'ss src :'$1'|awk \$0=\$5|tr .: +#|bc'
exec $0 $1

```

Not a serious solution, was just curious about this possibility.

Thanks to:

* ninjalj for suggesting the `awk` based filtering (-5 characters)

Sample run:

(terminal 1)

```
bash-4.3$ ./ip-reduce.sh 8080

```

(terminal 2)

```
bash-4.3$ nc localhost 8080
128

bash-4.3$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

```

On Ubuntu you can get `nc` from netcat-traditional (no, netcat-openbsd is not good) and `ss` from iproute2.
> 57 votes

# Answer
## Linux ELF/x86, 146 bytes

```
00000000  7f 45 4c 46 01 00 00 00  5a 0e 00 00 5a 5e eb 10  |.ELF....Z...Z^..|
00000010  02 00 03 00 0c 50 eb 10  0c 50 eb 10 04 00 00 00  |.....P...P......|
00000020  5e 53 43 53 52 89 e1 b0  66 3d 20 00 01 00 cd 80  |^SCSR...f= .....|
00000030  97 55 6b ed 0a 01 c5 ac  2c 30 79 f6 43 0f cd 01  |.Uk.....,0y.C...|
00000040  dd 55 89 e1 6a 10 51 6a  10 51 57 89 e1 b0 66 cd  |.U..j.Qj.QW...f.|
00000050  80 43 43 b0 66 cd 80 01  64 24 08 89 e1 43 b0 66  |.CC.f...d$...C.f|
00000060  cd 80 89 c1 93 8d 74 24  1b 99 fd ac 01 c2 e2 fb  |......t$........|
00000070  89 f7 b0 0a aa 91 92 f6  f1 86 c4 04 30 aa 42 c1  |............0.B.|
00000080  e8 08 75 f3 42 89 f9 41  b0 04 cd 80 b0 06 cd 80  |..u.B..A........|
00000090  eb c9                                             |..|
00000092

```

Includes a 52-byte ELF header, a 32-byte program header, 111 bytes of program code + 3 bytes of code for skipping around inside the headers.

Information on how to create tiny ELF executables can be found at breadbox's *"A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux"*.

Linux/i386 uses the `socketcall(2)` multiplex system call, which takes in `ebx` the specific socket call (the `SYS_*` macros from `/usr/include/linux/net.h`), and in `ecx` a pointer to the argument area of the original library call.

Some things done to keep the executable small:

* It assumes registers are zeroed on entry, which Linux does, but is not required by the ELF standard (the only requirement is that on entry `EDX` points to a finalization funtion (useful for executables loaded by the dynamic linker) or is NULL).
* It assumes on launch (typically by a shell) the only open file descriptors are 0, 1, and 2. Which means that the listening socket will be fd 3, and the accepted socket will be fd 4.
* It assumes there are exactly 2 arguments (including `argv[0]`).
* The same stack space is reused for the calls to `bind(2)`, `listen(2)` and `accept(2)`.
* To skip over the `phentsize` and `phnum` fields, a byte is prepended, turning into a `CMP` operation which takes the `phentsize` and `phnum` fields as an immediate (trick shamelessly stolen from breadbox's solution to 123 in anarchy golf).
* x86 string operations `LODS` (load into accumulator and increment/decrement source index) and `STOS` (store from accumulator and increment/decrement destination index) are nice for short code.
* `XCHG EAX, reg` is 1-byte, compared to `MOV EAX, reg`, which takes 2 bytes.
* `CDQ/CLTD` (sign-extend `EAX` into `EDX:EAX`) can be used as a 1-byte way to zero the `EDX` register.
* `BSWAP` is useful for implementing `htons()`.

Nasm source:

```
BITS 32                                         ;
                                                ;   ELF HEADER    --   PROGRAM HEADER
; ELF HEADER                                    ; +-------------+
DB 0x7f,'E','L','F'                             ; | magic       |    +--------------------+
                                                ; |             |    |                    |
; PROGRAM HEADERS                               ; |             |    |                    |
DD 1                                            ; |*class   32b | -- | type: PT_LOAD      |
                                                ; |*data   none |    |                    |
                                                ; |*version   0 |    |                    |
                                                ; |*ABI    SysV |    |                    |
DD 0xe5a        ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers    | -- | offset             |
                                                ; |             |    |                    |
entry:  pop     edx     ; edx = 2 (argc)        ; |*PADx7       | -- | vaddr = 0x10eb5e5a |
        pop     esi     ; discard argv[0]       ; |             |    |                    |
        jmp     short skip                      ; |             |    |                    |
DW 2                                            ; | ET_EXEC     | -- |*paddr LO           |
DW 3                                            ; | EM_386      | -- |*paddr HI           |
DD 0x10eb500c                                   ; |*version     | -- | filesz             |
DD 0x10eb500c                                   ; | entry point | -- | memsz              |
DD 4                                            ; | ph offset   | -- | flags: RX          |
                                                ; |             |    |                    |
skip:   pop     esi     ; esi = argv[1]         ; |*sh offset   | -- |*align              |
socket: push    ebx     ; default protocol (0)  ; |             |    |                    |
        inc     ebx                             ; |             |    |                    |
        push    ebx     ; SOCK_STREAM (1)       ; |             |    |                    |
        push    edx     ; AF_INET (2)           ; |*flags       |    +--------------------+
        mov     ecx, esp                        ; |             |
        mov     al, 0x66                        ; |*ehsize      |
DB 0x3d         ; cmp eax,0x10020               ; |             |
DW 32                                           ; | phentsize   |
DW 1                                            ; | phnum       |
                                                ; |             |
        int     0x80    ; socket(2, 1, 0)       ; |*shentsize   |
        xchg    edi, eax; edi = sockfd, eax = 0 ; |*shnum       |
        push    ebp     ; INADDR_ANY            ; |             |
                                                ; |             |
mult:   imul    ebp, 10 ; \_                    ; |*shstrndx    |
        add     ebp, eax; >                     ; |             |
        lodsb           ; >                     ; +-------------+
        sub     al,'0'  ; >
        jns     mult    ; / ebp = atoi(argv[1])                 ;       bind stack frame
                                                                ;    +-----------------------+
endmul: inc     ebx             ; SYS_BIND (2)                  ;    |        INADDR_ANY     |
                                                                ; +->| AF_INET | htons(port) |
        bswap   ebp                                             ; |  +-----------------------+
        add     ebp, ebx        ; AF_INET (2), htons(port)      ; |  |           16          |
        push    ebp                                             ; |  +-----------------------+
                                                                ; |  |         dummy         |
        mov     ecx, esp                                        ; |  +-----------------------+
        push    16              ; addrlen                       ; |  |           16          |
        push    ecx             ; dummy value                   ; |  +-----------------------+
        push    16              ; addrlen                       ; +--|          addr         |
        push    ecx             ; addr                          ;    +-----------------------+
        push    edi             ; sock                          ;    |         sockfd        |
        mov     ecx, esp                                        ;    +-----------------------+
        mov     al, 0x66
        int     0x80            ; bind(sockfd, addr, addrlen)
                                                                ;       accept stack frame
                                                                ;    +-----------------------+
listen: ;mov    byte [esp+8],1                                  ;    |        INADDR_ANY     |
        inc     ebx                                             ; +->| AF_INET | htons(port) |
        inc     ebx             ; SYS_LISTEN (4)                ; |  +-----------------------+
        mov     al, 0x66                                        ; |+>|           16          |
        int     0x80            ; listen(sockfd, backlog)       ; || +-----------------------+
                                                                ; || |         dummy         |
        add     [esp+8], esp                                    ; || +-----------------------+
accept: mov     ecx, esp                                        ; |+-|        &addrlen       |
        inc     ebx             ; SYS_ACCEPT (5)                ; |  +-----------------------+
        mov     al, 0x66                                        ; +--|          addr         |
        int     0x80            ; accept(sockfd, addr, &addrlen);    +-----------------------+
                                                                ;    |         sockfd        |
        mov     ecx, eax        ; ecx = 4                       ;    +-----------------------+
        xchg    ebx, eax        ; ebx = acceptfd, eax = 000000xx

        lea     esi, [esp+27]   ; point to the IP part of struct sockaddr_in
        cdq

        std                     ; reverse direction for string operations
addip:  lodsb                   ; \_
        add     edx, eax        ; > edx = sum of 4 IP bytes
        loop    addip           ; /

        mov     edi, esi        ; reuse struct sockaddr_in as scratch buffer
        mov     al, 10          ; '\n'
        stosb
        xchg    ecx, eax        ; ecx = 10
        xchg    eax, edx        ; edx = 0, eax = sum

divide: div     cl              ; \_
        xchg    al, ah          ; >
        add     al,0x30         ; >
        stosb                   ; > sprintf(scratch, "%d", sum)
        inc     edx             ; >
        shr     eax, 8          ; >
        jnz     divide          ; /

write:  inc     edx             ; ndigits + 1 ('\n')
        mov     ecx, edi
        inc     ecx
        mov     al,4
        int     0x80            ; write(acceptfd, scratch, scratchlen)
close:  mov     al, 6
        int     0x80            ; close(acceptfd)
        jmp     accept

```
> 25 votes

# Answer
# C#, ~~284~~ ~~283~~ ~~282~~ ~~278~~ ~~274~~ 254 bytes

```
class A{static int Main(string[]a){var b=new System.Net.Sockets.TcpListener(int.Parse(a[0]));b.Start();for(;;){var c=b.AcceptTcpClient();var d=c.Client.LocalEndPoint.Serialize();new System.IO.StreamWriter(c.GetStream()).WriteLine(d[4]+d[5]+d[6]+d[7]);}}}

```

Classic example of a basic C# TCP server. Testing:

**Terminal 1:**

```
$ ./Q76379.exe 1029

```

**Terminal 2:**

```
$ telnet localhost 1029
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

```

**Firefox:**
> 23 votes

# Answer
# NodeJS, ~~146~~ ~~134~~ 127 bytes

```
require('http').createServer((q,s)=>s.end(eval(0+q.socket.remoteAddress.replace(/^.*:|\./g,'+'))+'\n')).listen(process.argv[2])

```

I finally get to post a NodeJS answer! IPv4 only right now.

Sample execution: `node script.js 1024`. From another terminal:

```
$ curl 127.0.0.1:1024
128

```
> 16 votes

# Answer
# Tcl, 92

* 1 byte saved thanks to @DonalFellows.

```
proc s {c a p} {puts $c [expr [string map .\ + $a]]
close $c}
socket -server s $argv
vwait f

```

Fairly self-explanatory:

`socket -server s $argv` creates a listening socket on the port specified in the arguments.

Every time a new connection arrives, the `proc s` is called, with channel, source-address and source-port as parameters. `string map` substitutes `.` for `+` in the source address, and `expr` arithmetically evaluates the result, which is then `puts` back to the connection channel `c`.

`vwait` runs an event loop to catch the incoming connection events.

---

Credit to @DonalFellows for the following:

Here's a version that handles IPv6 (requires Tcl 8.6; most of the extra length is due to producing a hex response):

# Tcl, 109

```
proc s {c a p} {puts $c [format %x [expr 0x[string map :\ +0x0 $a]]]
close $c}
socket -server s $argv
vwait f

```
> 15 votes

# Answer
# Groovy 133, 125, 93, 89

```
new ServerSocket(args[0]as int).accept{it<<(it.inetAddress.address as int[]).sum()+"\n"}

```

IPv4 only, probably.

Ungolfed:

```
new ServerSocket(args[0]as int).accept{
    it << (it.inetAddress.address as int[]).sum()+"\n"
}

```

Testing:

```
$ telnet localhost 9000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

```
> 12 votes

# Answer
# Python 3, 170 166 147 bytes

```
from socket import*
s=socket()
s.bind(("",int(input())))
s.listen()
while 1:
 c,a=s.accept()
 c.send(b"%d\n"%eval(a[0].replace(".","+"))),c.close()

```

Takes port on `stdin`, IPv4 only. Works on GNU/Linux (and, I assume, most other unices), which automatically expands "" to "0.0.0.0", not sure about Windows though.
> 10 votes

# Answer
# Java, 371 368 350 344 333 310 295 282 bytes

## Golfed

```
import java.net.*;class A{public static void main(String[]n)throws Exception{ServerSocket s=new ServerSocket(Integer.decode(n[0]));for(;;){try(Socket a=s.accept()){byte[]c=a.getInetAddress().getAddress();new java.io.PrintStream(a.getOutputStream()).println(c[0]+c[1]+c[2]+c[3]);}}}}

```

### Ungolfed

```
import java.net.*;

class A {
    public static void main(String[] n) throws Exception {
        ServerSocket s = new ServerSocket(Integer.decode(n[0]));
        for (;;) {
            try (Socket a = s.accept()) {
                byte[] c = a.getInetAddress().getAddress();
                new java.io.PrintStream(a.getOutputStream()).println(c[0] + c[1] + c[2] + c[3]);
            }
        }
    }
}

```

### Output

```
mallard@steamroller:~$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

```
> 9 votes

# Answer
## PowerShell v2+, ~~303~~ ~~268~~ ~~257~~ 227 bytes

```
nal n new-object;($l=n Net.Sockets.TcpListener($args[0])).Start()
for(){($w=n IO.StreamWriter(($c=$l.AcceptTcpClient()).GetStream())).Write((([Net.IPEndPoint]$c.Client.RemoteEndPoint).Address-replace"\.",'+'|iex))
$w.Dispose()}

```

Saved 35 bytes thanks to Matt ... Saved another 11 bytes by aliasing `New-Object` and minor tweaks ... Saved 30 more bytes by implicitly using localhost rather than `any` IP address and corrected to account for continual usage as originally specified and I missed

Really similar to the C# answer, since it's .NET underlying both. We save a few bytes here over the C# answer by being able to leverage the returning functionality of PowerShell (surrounding our declaration/assignment in parens, and then immediately calling the . methods), but we lose an awful lot by needing to formulate the summation. The fact that we've got slightly shorter class names/calls is really why this answer is beating C#.

### Explanation

We first create a `New-Alias` (with the `nal` alias) to save on re-typing `New-Object` later. The rest of the first line is setting up a TCP Listener. We pass the command-line `$args[0]` as the input for creating a new `System.Net.Sockets.TcpListener`, stored as `$l`. That object is encapsulated in parens and immediately called with `.Start()` to have it actively open the socket.

Entering an infinite `for` loop, we then set our listener `$l` to blocking with `AcceptTcpClient()` which will wait for a connection. A reference to that connection (once it's made) is stored in `$c`, encapsulated in parens, and immediately called `GetStream()` to get the datastream. That datastream is passed to a new `System.IO.StreamWriter` constructor, `$w`, so we can manipulate it. That constructor is itself encapsulated in parens and immediately called `Write(...)`.

Inside the `Write(...)` call, we take our client handle `$c` and obtain the client's `RemoteEndPoint` property. This is the only way (that I've found so far) to get the remote IP address. Next we need to re-cast that as a `[System.Net.IPEndPoint]` object so it's formatted correctly, encapsulate that in parens, and pull just the `.Address` property. We then `-replace` the literal periods with plus signs, then pipe it to `Invoke-Expression` (similar to `eval`) to obtain our summation.

After the IO write, we need to call `.Dispose()` to ensure the datastream is flushed to the client and closed. The TCP server drops the client connection without warning, so depending upon the client used it may hang for a while at this point. It then continues through the `for` loop without properly closing connections. This also means that it leaks memory and system handles like crazy, but we don't care about that, right? You may need to use Task Manager to kill the process when you're done running the server, though. :D

Also IPv4 only, as the summation barfs spectacularly trying to handle an IPv6 address, since `:` isn't a valid algebraic operator for `iex` to parse.
> 8 votes

# Answer
# Go, ~~359~~ 311

This is my first program in Go - It allowed to let me discover one thing : This is definitively not a good golfing language!

(Kudos to @steve who did most of the golfing !)

```
package main
import(n"net";t"strings";r"strconv";x"regexp";"os")
func main(){l,_:=n.Listen("tcp",":"+os.Args[1])
for{c,_:=l.Accept();var s int
for _,i:=range t.Split(x.MustCompile(":[0-9]+$").ReplaceAllLiteralString(c.RemoteAddr().String(),""),"."){
n,_:=r.Atoi(i);s=s+n};c.Write([]byte(r.Itoa(s)));c.Close()}}

```
> 7 votes

# Answer
## Common Lisp, 110 bytes

```
(use-package'usocket)(lambda(p)(socket-server"localhost"p(lambda(u)(format u"~D~%"(reduce'+ *remote-host*)))))

```

## Details

```
(use-package 'usocket)

(lambda (port)

  ;; create server with event-loop
  (socket-server "localhost"
                 port

                 ;; tcp-handler
                 (lambda (stream)
                   ;; format to stream to client
                   (format stream
                           "~D~%"
                           ;; add all elements of the host,
                           ;; a vector of 4 integers
                           (reduce #'+ *remote-host*))

                   ;; client connection is closed automatically
                   ;; when exiting this function
                 )))

```
> 7 votes

# Answer
# PHP, 161 (56?)

This is my first post in here. I hope this goes right :)

```
<?php $s=socket_create_listen($argv[1]);while($c=socket_accept($s)){socket_getpeername($c,$r);socket_write($c,array_sum(explode('.',$r))."\n");socket_close($c);}

```

**Ungolfed:**

```
<?php
    $s = socket_create_listen($argv[1]); //Create socket
    while( $c = socket_accept($s) ) { // Loop accepting new connections
        socket_getpeername($c, $r); // Get IP address in $r
        socket_write($c, array_sum(explode('.', $r))."\n"); //Calculate sum
        socket_close($c); //Close connection and wait for next one
    }

```

**Terminal:**

```
$ php test.php 8080 &
$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.

```

This only works for IPV4

**Edit**: I just noticed that php supports basic server:
I decided stick to original character count unless somebody confirms if following is allowed :)

test2.php: (possible 56-byte solution)

```
<?=array_sum(explode('.',$_SERVER['REMOTE_ADDR']))."\n";

```

And then start service with:

```
php -S localhost:8080 test2.php

```

**Chrome as client**

**Edit 2: wget as client**

```
$ wget -qO- localhost:8080
128

```
> 7 votes

# Answer
# LiveScript, ~~107~~ 105 bytes

```
(require \http)createServer(->&1.end((.reduce (+))<|it.connection.remoteAddress/\.))listen process.argv.0

```

Nothing much to add, it's just basic NodeJS stuff. Style points for `&1` (second argument), `<|` (F# piping, akin to `$` in Haskell) and biop: `(+)` in LS is like operator sections in Haskell: a curried binary function (that adds its operands). Also a bit dirty: `/`, if given a *literal* string on its right, will do split.
> 6 votes

# Answer
# q, 88 bytes

```
system raze"p ",1_.z.x;.z.pg:{(string sum"i"$0x0 vs .z.a),"\n"};.z.ph:{.h.hy[`;.z.pg[]]}

```
* `system raze"p ",1_.z.x`: Takes the second command-line argument (the first `"-"` is for telling `q` not to interpret `N` as a script/file) and opens a port (`"p "`) with it.
    + Note: Calling `q -p N` sets the port as `N` automatically, but since the question seems to suggest that `N` should be an argument to the program rather than the executable itself, I've gone the longer way.
* Inside the `.z.pg` function that handles incoming requests, `.z.a` holds the IP address as a 32-bit integer.
    + `"i"$0x0 vs` splits it into its integer 'constituents', and `sum` does the summation.
    + Last, `string` the numeric result and append `"\n"` to it to return to the client.
* `.z.ph` is another function for HTTP GET requests, with extra handling to convert the string output into a valid HTTP response.

Demo - Server:

```
c:\q\w32>q - 1234
KDB+ 3.3 2015.11.03 Copyright (C) 1993-2015 Kx Systems
w32/ 4()core ... NONEXPIRE

Welcome to kdb+ 32bit edition
q)system raze"p ",1_.z.x;.z.pg:{(string sum"i"$0x0 vs .z.a),"\n"};.z.ph:{.h.hy[`;.z.pg[]]}
q)

```

Demo - Client (from another `q` session running on `127.0.0.1`):

```
q)(hopen `::1234)""
"128\n"

```

Demo - Client (from `curl`):

```
$ curl localhost:1234
128

$

```
> 6 votes

# Answer
# 8086 machine code (16-bit DOS), ~~163 156 148 148~~ 142 bytes

```
00000000  31 c0 bb 0a 00 31 c9 be  81 00 bf 80 00 8a 0d 01  |1....1..........|
00000010  cf 46 8a 0c 80 e9 30 f7  e3 00 c8 39 fe 72 f2 89  |.F....0....9.r..|
00000020  c3 89 c1 b8 01 10 ba ff  ff 31 f6 31 ff cd 61 53  |.........1.1..aS|
00000030  b8 00 12 bf 80 00 b9 01  00 ba ff ff cd 61 b8 00  |.............a..|
00000040  14 cd 61 31 c0 bb 0a 00  83 c7 06 8d 4d 04 26 02  |..a1........M.&.|
00000050  05 80 d4 00 47 39 cf 72  f5 bf 84 00 b9 80 00 bb  |....G9.r........|
00000060  0a 00 4f 31 d2 f7 f3 80  c2 30 88 15 39 cf 77 f2  |..O1.....0..9.w.|
00000070  1e 07 b8 0e 13 5b bf 80  00 b9 04 00 ba ff ff cd  |.....[..........|
00000080  61 b8 00 11 ba 01 00 cd  61 b8 00 4c cd 21        |a.......a..L.!|
0000008e

```

Equivalent assembly code:

```
org 0x100
tcp equ 0x61    ; NTCPDRV interrupt

    xor ax,ax
    mov bx,10
    xor cx,cx
    mov si,0x81     ; [ds:81]-[ds:FF] = command line args
    mov di,0x80     ; [ds:80] = strlen(args)
    mov cl,[di]
    add di,cx

@@: inc si
    mov cl,[si]     ; get character
    sub cl,'0'      ; convert char to int
    mul bx          ; ax *= 10
    add al,cl
    cmp si,di
    jb @b
    ; now ax = port number

    mov bx,ax       ; source port (leaving this 0 doesn't work?)
    mov cx,ax       ; dest port
    mov ax,0x1001   ; open TCP socket for listening
    mov dx,-1       ; infinite timeout
    xor si,si       ; any dest IP
    xor di,di
    int tcp
    ; ^ I think this call should block until a connection is established, but apparently it doesn't.

    push bx         ; bx = socket handle, save it for later

    mov ax,0x1200   ; read from socket
    mov di,0x80     ; es:di = buffer (just reuse argument area to save space)
    mov cx,1        ; one byte
    mov dx,-1
    int tcp         ; this will block until a client connects and sends one byte

    mov ax,0x1400   ; get TCP session status, bx=handle
    int tcp
    ; now es:di points to a struct containing the source/dest IP addresses and ports
    ; the docs say it's two dwords for each IP address, then two bytes for "ip_prot" and "active" (whatever that means)
    ; ...but actually each IP address is followed by the port number (one word)

    xor ax,ax
    mov bx,10
    add di,6        ; [es:di+6] = client IP
    lea cx,[di+4]
@@: add al,[es:di]  ; add all bytes together
    adc ah,0
    inc di
    cmp di,cx
    jb @b
    ; now ax contains the IP address sum

    mov di,0x84     ; recycle arguments area again
    mov cx,0x80
    mov bx,10
@@: dec di
    xor dx,dx
    div bx          ; dl = ax mod 10
    add dl,'0'      ; convert int to char
    mov [di],dl
    cmp di,cx
    ja @b
    ; now [ds:80]-[ds:83] contains an ascii representation of the IP address sum

    push ds
    pop es
    mov ax,0x130e   ; send data with newline, wait for ack
    pop bx          ; socket handle
    mov di,0x80     ; es:di = data
    mov cx,4        ; sizeof data
    mov dx,-1
    int tcp

    mov ax,0x1100   ; close TCP socket
    mov dx,1
    int tcp

    mov ax,0x4c00
    int 0x21

```

This assumes `ntcpdrv` is loaded at `INT 0x61` (and any suitable packet driver at `0x60`). Compile with `fasm tcpserv.asm`.

It has some issues though:

* It doesn't check if the argument is a valid port number, or if it's even a number at all.
* The client must send at least one byte, since I can't seem to find any other way to tell if a client has connected.
* It only works once, and hangs on a second attempt. Works again after a reboot.
* The returned value is left-padded with zeroes.
* This is my very first code golf entry, and also my very first 8086 asm program. I'm sure there are ways to improve this further.
> 6 votes

# Answer
# Perl, ~~141~~ 132 + 1 = 133 bytes

## Golfed

```
$s=new IO::Socket::INET LocalPort=><>,Listen=>5,Reuse=>1;{$c=$s->accept;$_=$c->peerhost;y/./+/;$c->send(eval.$/);shutdown $c,1;redo}

```

## Ungolfed

```
# listen on tcp port obtained from stdin
$s=new IO::Socket::INET(LocalPort=> <>,
                        Listen   => 5,
                        Reuse    => 1);

{
    # accept connection
    $c=$s->accept();

    # get the ip address
    $_=$c->peerhost();

    # replace dots with plus
    y/./+/;

    # send the evaluated version back, with a newline
    $c->send(eval . $/);

    # close
    shutdown($c,1);

    redo;
}

```

## Example

```
$ echo 7777|perl -MIO::Socket::INET -e'$s=new IO::Socket::INET LocalPort=><>,Listen=>5,Reuse=>1;{$c=$s->accept;$_=$c->peerhost;y/./+/;$c->send(eval.$/);shutdown $c,1;redo}'

$ telnet 127.0.0.1 7777
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
128
Connection closed by foreign host.
$

```
> 5 votes

# Answer
# NodeJS (ES6), ~~129~~ ~~118~~ 107 bytes

```
require('net').createServer(c=>c.end(eval(c.remoteAddress.replace(/\./g,'+'))+`
`)).listen(process.argv[2])

```

Works for IPv4. Run as `node server.js <port>`
> 4 votes

# Answer
## PowerShell, 208 206 192 152 bytes

```
($t=[net.sockets.tcplistener]$args[0]).start();for(){($z=$t.acceptsocket()).send([char[]]"$($z.remoteendpoint.address-replace"\.","+"|iex)");$z.close()}

```

version information:

```
Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34209
BuildVersion                   6.3.9600.17400
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

```

Thanks to TimmyD for saving me 14 bytes!

Massive thanks to TessellatingHeckler for saving me 40 bytes
> 4 votes

# Answer
# Python 2, 180 bytes

```
from SocketServer import*
TCPServer(('',input()),type('',(BaseRequestHandler,set),{'handle':lambda s:s.request.send(`eval(s.client_address[0].replace('.','+'))`)})).serve_forever()

```

Takes the port over stdin.
> 4 votes

# Answer
## Go, 211 bytes

```
package main
import(."fmt"
."net"
"os")
func main(){s,_:=Listen("tcp4",":"+os.Args[1])
for{c,_:=s.Accept()
var a,b,d,e int
Sscanf(Sprint(c.RemoteAddr()),"%d.%d.%d.%d",&a,&b,&d,&e)
Fprintln(c,a+b+d+e)
c.Close()}}

```

Can probably be golfed further, I'm not entirely satisfied with the way I have to parse the IP adress for instance, it looks like a horrible hack.

Listens on IPv4 on the port given as argument.
> 4 votes

# Answer
## C, 535 bytes

Well, someone had to do this.

I added a single line break so the posted code actually has 536 characters.

```
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
int main(int c,char**v){int f,l;char b[99];struct sockaddr_in d,e;f=socket(AF_INET,SOCK_STREAM,0);bzero(&d,sizeof(d));d.sin_family=AF_INET;d.sin_addr.s_addr=INADDR_ANY;d.sin_port=htons(atoi(v[1]));bind(f,&d, sizeof(d));listen(f,5);l=sizeof(e);
f=accept(f,&e,&l);bzero(b,99);int p,q,r,s;char g[INET_ADDRSTRLEN];inet_ntop(AF_INET,&(e.sin_addr),g,INET_ADDRSTRLEN);sscanf(g,"%d.%d.%d.%d",&p,&q,&r,&s);sprintf(b,"%d\n",p+q+r+s);write(f,b,strlen(b));return 0;}

```

compile with `gcc [file_name] -o server`

run with `./server [port]`

connect with `telnet localhost [port]`
> 4 votes

# Answer
# Mumps, ~~114~~ 115 Bytes

Golfed:

```
R P F{S J=0,I="|TCP|1" O I:(:P) U I R K F K=1:1:4{S J=J+$P(##class(%SYSTEM.TCPDevice).PeerAddr(),".",K)} W J,! C I}

```

Ungolfed:

```
R P             ; Read Port # from STDIN ;
  F{            ; Loop over everything;
  S J=0,        ; Initial IP segment total
  I="|TCP|1"    ; TCP device
  O I:(:P)      ; Open the TCP device, port from input {and sticking a tongue out! :-) }
  U I           ; Use the TCP device
  R K           ; Read from STDIN (anything)
  F K=1:1:4{    ; Iterate 1->4 in variable K
    S J=J+      ; Accumulate the following segments of the IP in var. J
    $P(##class(%SYSTEM.TCPDevice).PeerAddr(),".",K) ; Grab each piece of IPv4.
            }   ; close the loop.
  W J,!         ; Write the total w/newline out the TCP port
  C I           ; close the TCP port to send.
}               ; end final loop

```

This is the InterSystems Caché version of Mumps - if there's a version out there that can acquire the TCP address shorter than `##class(%SYSTEM.TCPDevice).PeerAddr()` *(as it's almost a 1/3 of the entire program)* it might have a better chance against some of the other languages posted already... ;-)

Edit: Thanks to @TimmyD - I missed the reading of the port from STDIN or arguments instead of being hardcoded. Edited; it added 1 byte to the program.
> 3 votes

# Answer
# Haskell, 216 bytes

Using the "network-simple" package (`cabal install network-simple`). Needs a couple of language extensions (`-XOverloadedStrings -XNoMonomorphismRestriction`) to work.

```
import Network.Simple.TCP(serve)
import Network.Socket
import Data.Bits
main=getLine>>= \n->serve"*"n p
p(s,(SockAddrInet _ h))=()<$(send s$(show$sum$w h 24)++"\n")
m=255
w h 0=[h.&.m]
w h n=h`shiftR`n.&.m:(w h$n-8)

```

There are a couple of possible simplifications, including changing the `w` function to return the sum directly rather than a list, and using a function rather than a program so that the port number can be specified as an argument. I don't imagine this would reduce the size very much, though. 20 bytes perhaps?
> 3 votes

# Answer
# C, 243 188 bytes (or perhaps 217 162 bytes)

V2: see below for the explanations.

188 bytes:

```
s;main(g,v)char**v;{short S[8]={2,htons(atoi(v[1]))};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}

```

Slightly circumspect 162 bytes:

```
s;main(g){short S[8]={2,g};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}

```

Probably more golfing possible tomorrow morning. I'll tidy this post up after those updates.

---

V1:

This one was really quite fun to golf.

```
#include<netdb.h>
s,c,q;main(g,v)char**v;{struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}

```

It works for IPv4. Mostly it's a straightforward implementation. The three main components are

Creating the socket:

```
struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);

```

We use the various explicit forms of the constants AF\_INET etc, and make use of the fact that when a struct is initialised in C in this way the non-specified elements are set to zero.

Listen for clients, accept them, and close their connections:

```
for(listen(s,8);c=accept(s,&C,&g);q=fclose(g))

```

Finally to send each client the data:

```
for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);

```

The IP is stored in `C.sin_addr.s_addr` as a 32 bit integer where each octet is represented by one of the four bytes. We sum these bytes with the for loop and then print them to the stream using fprintf.

I have a shorter 217 byte solution but I'm not entirely sure it doesn't violate the standard loopholes since it requires that the port is given in unary in network byte order as command line arguments. That is, to run the server on port 12345 one would need to call

```
$ ./tcp 1 1 1 1 ... 1 1 1

```

where the total number of `1`s is 14640. To say the least it's a little... cumbersome. But here it is anyway:

```
#include<netdb.h>
s,c,q;main(g){struct sockaddr_in S={2,g},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}

```
> 3 votes

# Answer
# Java, ~~283~~ 275 bytes

**Golfed**

```
import java.net.*;class A{public static void main(String[] n)throws Exception{ServerSocket s=new ServerSocket(Integer.valueOf(n[0]));for(;;)try(Socket a=s.accept()){int v=0;for(byte b:a.getInetAddress().getAddress())v+=b&255;a.getOutputStream().write((v+"\n").getBytes());}}}

```

**Ungolfed**

```
import java.net.*;

class A {
public static void main(String[] n) throws Exception {
    ServerSocket s = new ServerSocket(Integer.valueOf(n[0]));
    for (;;)
        try (Socket a = s.accept()) {
            int v = 0;
            for (byte b : a.getInetAddress().getAddress())
                v += b & 255;
            a.getOutputStream().write((v + "\n").getBytes());
        }
}
}

```

**Edit:** Down to 274 thanks to @ogregoire
> 2 votes

# Answer
# Java, 210 bytes

Golfed:

```
p->{java.net.ServerSocket x=new java.net.ServerSocket(p);for(;;){try(java.net.Socket s=x.accept()){byte[]b=s.getInetAddress().getAddress();s.getOutputStream().write((0+b[0]+b[1]+b[2]+b[3]+"\n").getBytes());}}};

```

Expanded:

```
@FunctionalInterface interface Consumer { // Define an interface that allows a function that throws an exception.
  void accept(int port) throws Exception;
}

Consumer consumer = (port) -> {
  java.net.ServerSocket serverSocket = new java.net.ServerSocket(port);
    for (;;) {
      try (java.net.Socket socket = serverSocket.accept()) {
        byte[] bytes = socket.getInetAddress().getAddress();
        socket.getOutputStream().write((0 + b[0] + b[1] + b[2] + b[3] + "\n").getBytes());
      }
    }
}

```

This a gathering of all the tips I gave in other Java answers, plus the writing as a function instead of a full program, which gains roughly 70 bytes compared to the program.
> 2 votes

# Answer
# Lua, ~~169~~ ~~162~~ ~~160~~ ~~153~~ ~~151~~ ~~148~~ ~~138~~ 129 bytes

**Golfed version**

```
m=require"socket".bind(0,...)::l::c=m:accept()f=0 for n in c:getpeername():gmatch"%d+"do f=f+n end c:send(f.."\n")c:close()goto l

```

It requires Luasocket to be installed and an interpreter that supports labels. I've tested it with Luajit and I can also confirm that the code does not work with Lua 5.1.

**Ungolfed version**

```
m=require"socket".bind(0,...)
::l::
c=m:accept()

f=0
for n in c:getpeername():gmatch"%d+" do
    f=f+n
end
c:send(f.."\n")

c:close()
goto l

```

**Edit 1:**

Changed `i=({c:getpeername()})[1]` to just `i=c:getpeername()`

**Edit 2:**

Removed braces from the require statement.

**Edit 3:**

Removed the braces around the vararg, decreased the byte count a little bit.

**Edit 4:**

Removed the parenthesis around "%d+", shorter by 2 bytes.

**Edit 5:**

Removed the unnecessary variable i.

**Edit 6:**

Changed the ip from "127.0.0.1" to 0. (Thanks to xyzzy on #lua)

**Edit 7:**

Removed the function call to tonumber since strings are cast to numbers automatically (Thanks to Trebuchette for the suggestion, I did not know this)
> 2 votes

# Answer
# Haskell, 326 bytes

```
import Data.Bits
import Network.Socket
import System.IO
f n=withSocketsDo$do
 s<-socket AF_INET Stream defaultProtocol
 bind s$SockAddrInet n iNADDR_ANY
 listen s 1
 g s
g s=do
 (z,SockAddrInet _ a)<-accept s
 h<-socketToHandle z WriteMode
 hPutStrLn h$show$b a
 hClose h
 g s
b 0=0
b x=x.&.0xFF+b(x`shiftR`8)

```

Sadly I had to use `Network.Socket` to get access to the remote IP address as an integer rather than a string. It would have saved dozens of characters if I could just do `s <- listenOn (PortNumber n)`, rather than having to explicitly call `socket`, `bind` and `listen` individually. But, sadly, `Network.accept` gives me a host *string*, not an IP address *integer*, so I had to resort to `Network.Socket.accept` and friends.

The function `f` takes a port number as argument, and creates a server socket (`s`) listening on that port. It then calls the function `g` with the server socket. `g` loops forever, accepting connections. The function `b` takes an actual IPv4 address and computes the sum of its digits.

I'm sure somebody somewhere can do this better than me. I wanted to show off just how damned easy socket stuff is in Haskell... but then failed miserably, because I need access to the IP address, which isn't usually easy to get.
> 2 votes

# Answer
# Haskell, 185 (+ 19 = 204)? bytes

```
import Network.Simple.TCP(serve)
import Network.Socket
import Data.List.Split
main=getLine>>=flip(serve"*4")(\(a,b)->()<$(send a$(++"\n")$show$sum.map read.take 4.sepByOneOf":."$show b)

```

Takes port number as one line on stdin; requires `network-simple` from Cabal.

As usual with Haskell answers that don't constrain themselves to pure functions, the `imports` take up far too many bytes. The trailing newline is also worth 9 bytes...

Somewhat similar to @Jules's answer, but I use string manipulation instead of byte operations. I ~~stole~~ used the `-XOverloadedStrings` extension as well, which is probably worth 19 bytes extra.
> 2 votes

# Answer
# Factor, ~~155~~ ~~146~~ ~~131~~ ~~206~~ 190 bytes

Well, I just learned a lot about low-level socket programming. I don't think I ever wanna do that again, because my ~~thr~~head hurts.

```
[ utf8 <threaded-server> readln 10 base> >>insecure [ remote-address get host>> "." split [ 10 base> ] map sum 10 >base print flush ] >>handler [ start-server ] in-thread start-server drop ]

```

Oh yeah, threaded, and doesn't return, right.
> 2 votes

# Answer
# Racket, 265 bytes

```
#lang racket(define l(tcp-listen(string->number(read-line))))(let e()(define-values(i o)(tcp-accept l))(thread(λ()(define-values(a b)(tcp-addresses o))(write(~a(foldl + 0(map string->number(string-split a".")))o))(newline o)(close-output-port o)))(e)))

```

Ungolfed:

```
#lang racket
(define listener (tcp-listen (string->number (read-line))))
(define (mk-server)
  (let echo-server ()
    (define-values (in out) (tcp-accept listener))
    (thread
     (λ()
       (define-values (a b) (tcp-addresses out))
       (write (number->string (foldl + 0(map string->number(string-split a "."))) out))
       (write "\n" out)
       (close-output-port out)))
    (echo-server)))

```
> 2 votes

# Answer
# Matlab, 128 139 Bytes

Listens on port n, Ipv4 only (even if it listens on IPv6 too).

```
function m(n);while 1;t=tcpip('0.0.0.0',n,'NetworkRole','server');fopen(t);fprintf(t,'%d\n',sum(sscanf(t.RemoteHost,'%d.')));fclose(t);end

```
> 1 votes

# Answer
# k (55 characters)

This is essentially a translation of @h.j.k. solution in q with a couple of modifications.

```
."\\p ",*.z.x
.z.pg:{$+/0x0\:.z.a}
.z.ph:.h.hy[`].z.pg@

```

Usage: `q filename.k PORT`
> 1 votes

# Answer
# AutoIT, ~~308~~ ~~293~~ ~~281~~ ~~278~~ ~~275~~ ~~274~~ ~~272~~ ~~270~~ 264 bytes

```
Func K($n)
TCPStartup()
$A=TCPListen("127.0.0.1",$n)
Do
$B=TCPAccept($A)
Until $B>0
While 1
$C=TCPRecv($B,$n)
If $C Then
$e=StringInStr($C,"st:")+4
$d=stringsplit(StringMid($C,$e,StringInStr($C,":")-$e),".")
ConsoleWrite($d[1]+$d[2]+$d[3]+$d[4])
EndIf
WEnd
EndFunc

```

Script-Example.com has an online compiler.

Reusing the port variable ($n) in the TCPRecv max-length parameter. Since it is never going to be less than 1024, it's saving me a byte.
> 1 votes

# Answer
# Rust, 185 bytes

```
use std::{io::*,net::*};|a|while let Ok((mut a,SocketAddr::V6(b)))=TcpListener::bind(("::",a)).unwrap().accept(){write!(a,"{:x}
",b.ip().segments().map(|a|a as _).iter().sum::<u32>());}

```

This is a closure of type `fn(u16)`. It accepts IPv6 connections and formats its output in hexadecimal. Golfing in Rust can be pretty challenging due to the number of transformations allowed by the compiler. Rust 1.55.0 or higher is necessary to compile this program.
> 1 votes

# Answer
# LispyScript, 196 bytes

```
(->(require"http")(.createServer(function(q r)(r.end((str(-> (r.socket.remoteAddress)(.split".")(.map parseFloat)(.reduce (function(x y)(+ x y)))))'\n')(.listen(get 2 process.argv)"127.0.0.1"))))

```

If it looks like one of the Node submissions above, that's because it's pretty much just Node with a prettier face.

Ungolfed:

```
(->
  (require "http")
  (.createServer
    (function (request response)
      (response.writeHead 200 {'Content-Type': 'text/plain'})
      (response.end
        (str (-> (request.socket.remoteAddress)
             (.split ".")
             (.map parseFloat)
             (.reduce (function (x y) (+ x y)))))
          '\n')
  (.listen (|| (get 2 process.argv) 1337) "127.0.0.1"))))

```

Two functions, two method chains.
> 0 votes

# Answer
# NodeJS, (IPv4 and IPv6) 105 Bytes

```
require("net").createServer(s=>s.end(eval(s.remoteAddress.replace(/[:.]/g,"+"))).listen(process.argv[2])

```

Explanation:

```
require("net")               # TCP library
 .createServer(              # Create the server
   s=>                       # Socket is s
    s.end(                   # Print and end the connection
     eval(                   # Treat the following string like JavaScript
      s.remoteAddress        # The IP address (IPv4 or IPv6, depending on connection)
       .replace(/.|:/g, "+") # Replace all . and : with +
 )))                         # Close server response
 .listen(process.argv[2])    # Listen on the third index of the arg array (["node", "filename.js", "first arg"])

```
> 0 votes

# Answer
## Common LIsp (Lispworks), 564 bytes

```
(require "comm")(defun make-stream-and-talk(handle)(let((stream(make-instance 'comm:socket-stream :socket handle :direction :io :element-type 'base-char)))(mp:process-run-function(format nil "" handle) '() 'f stream)))(defun f(stream)(unwind-protect(progn(multiple-value-bind(address port)(comm:socket-stream-address stream)(declare(ignore port))(format stream "~S"(reduce #'+(mapcar #'parse-integer(split-sequence "."(comm:ip-address-string address)))))(force-output stream))(close stream))))(comm:start-up-server :function 'make-stream-and-talk :service 10246)

```

ungolfed:

```
    (require "comm")
    (defun make-stream-and-talk (handle)
      (let ((stream (make-instance 'comm:socket-stream
                                   :socket handle
                                   :direction :io
                                   :element-type
                                   'base-char)))
        (mp:process-run-function (format nil ""
                                         handle)
                                 '()
                                 'f stream)))

    (defun f (stream)
      (unwind-protect
          (progn
            (multiple-value-bind (address port)
                (comm:socket-stream-address stream)
              (declare (ignore port))
              (format stream "~S"
                      (reduce #'+
                              (mapcar #'parse-integer
                                      (split-sequence "."
                                                      (comm:ip-address-string address)))))
              (force-output stream))
            (close stream))))

    (comm:start-up-server :function 'make-stream-and-talk
                          :service 10246)

```

Usange:

```
    c:\~]$ telnet 127.0.0.1 10246

    Connecting to 127.0.0.1:10246...
    Connection established.
    To escape to local shell, press 'Ctrl+Alt+]'.
    you sent: 128
    Connection closed by foreign host.

    Disconnected from remote host(127.0.0.1:10246) at 23:42:56.

    Type `help' to learn how to use Xshell prompt.

```

Note:

```
reference Lispworks documents

```
> 0 votes

# Answer
# Object Pascal, ~~342~~ 340 bytes

A small (well the pascal definition of small...) server with the lowest level Sockets library. Listenes to IP4, port no. on the commandline.

```
uses sockets;var s,c,l,i,f:integer;a,b:TInetSockAddr;g:string;begin val(ParamStr(1),f,i);s:=fpSocket(2,1,0);a.sin_family:=2;a.sin_port:=ntobe(f);l:=sizeof(a);fpBind(s,@a,l);repeat fpListen(s,1);c:=fpaccept(s,@b,@l);f:=0;for i:=1to 4do f:=f+b.sin_addr.s_bytes[i];Str(f,g);g:=g+#10;fpsend(c,@g[1],length(g),0);fpshutdown(c,2);until False;end.

```

Ungolfed:

```
uses
  sockets;
var
  s, c, l, i, f: integer;
  a, b: TInetSockAddr;        { a=server, b=client }
  g: string;
begin
  val(ParamStr(1), f, i);     { store port no. in f }
  s := fpSocket(2, 1, 0);     { 2=AF_INET, 1=SOCK_STREAM, 0=PF_UNSPEC }
  a.sin_family := 2;          { 2=AF_INET }
  a.sin_port := ntobe(f);     { port to listen to, address initialized to localhost by default }
  l := sizeof(a);
  fpBind(s, @a, l);           { bind socket to address:port }
  repeat
    fpListen(s ,1);           { listen for one incoming connection }
    c := fpaccept(s, @b, @l); { accept connection, client address in b }
    f := 0;
    for i:=1 to 4 do
      f := f+b.sin_addr.s_bytes[i]; { add 4 bytes of client address }
    Str(f, g);                      { store f in a string }
    g := g+#10;                     { add newline }
    fpsend(c, @g[1], length(g), 0); { send the addition result }
    fpshutdown(c, 2);               { close the connection }
  until False;
end.

```
> 0 votes

# Answer
# Racket, 174 bytes

```
(do([l(tcp-listen 1234)])(#f)(let*-values([(i o)(tcp-accept l)][(a b)(tcp-addresses i)])(displayln(for/sum([s(string-split b".")])(string->number s))o)(close-output-port o)))

```

## Ungolfed

```
(do ([l (tcp-listen 1234)])
    (#f)
  (let*-values ([(i o) (tcp-accept l)]
                [(a b) (tcp-addresses i)])
    (displayln
     (for/sum ([s (string-split b ".")])
       (string->number s))
     o)
    (close-output-port o)))

```

Shoutout to cat for bringing the Racket competition!
> 0 votes

---
Tags: code-golf, internet, networking
---


title: Unlolify a lolified message

text:
# Question
Title: Unlolify a lolified message
Unlolify a lolified message!

I had to ask a coworker if they wanted to have lunch with me, but we're both hackers so it could not be in a lame way. The message asking that was roughly this:

> please respond with `011110010110010101110011` if you'd like to join lunch today

The colleague being a hacker, just responded with `0x796573`, to which I responded back:

> 0x636f6f6c2c206e696365

To save my colleague the trouble of unlolifying it, I wrote a Ruby function to unlolify and sent it along with the message. But the function itself was way more lengthier than the lolified message itself. I'd like to have a better alternative in the future and be able to send a much shorter `unlolify` function.

Can someone help me? :-)

# The challenge

A lolified message (valid examples above) is just an integer number. Unlolify it by first getting the binary string representation of the number, then left-padding it with the character `0` (zero) as many times as necessary so that the string length is a multiple of 8. Then take each sequence of 8 digits (from left to right) and convert each one of them to its corresponding ASCII character (the digits form a binary representation of an integer). Finally, put together all the resulting characters so that they represent a text string.

The challenge is to write the code of the function `unlolify`, which takes a positive integer number as input and outputs the unlolified string.

For example, the lolified hexadecimal number `636f6f6c2c206e696365` will output the string `cool, nice`.

**Rules:**

1. Output strings will always contain only ASCII characters. Thus, each character is exactly one byte long
2. The number of bits of the input can be arbitrarily high
3. The input must be a positive integer number (`input > 0`)

Standard rules apply.

# Answer
> 31 votes
# Vyxal, 3 bytes

```
₈τC

```

Try it Online!

```
 τ  # Convert to base...
₈   # 256
  C # Get charcodes

```

# Answer
> 15 votes
# dc, 2 bytes

```
?P

```

Try it online!

A full program that `?` reads input as an integer and `P` prints the string resulting from the operation specified in the challenge.

From its manual page:

```
   P      Pops  off  the  value  on top of the stack.  If it it a string, it is simply printed without a trailing newline.
          Otherwise it is a number, and the integer portion of its absolute value is printed out as a "base (UCHAR_MAX+1)"
          byte  stream.  Assuming that (UCHAR_MAX+1) is 256 (as it is on most machines with 8-bit bytes), the sequence KSK
          0k1/ [_1*]sx d0>x [256~aPd0<x]dsxx sxLKk could also accomplish this function,  except  for  the  side-effect  of
          clobbering the x register.

```

If the input can be assumed to be left on the stack, then just `P` would work for 1 byte.

# Answer
> 8 votes
# Vyxal, 9 bytes

```
bṘ8ẇṘRvBC

```

Try it Online!

*-6 thanks to @emanresuA*

Well frick. I got played.

# Answer
> 8 votes
# C (clang), <sup>~~31~~ \\$\cdots\\$ ~~28~~</sup> 21 bytes

```
f(a,n){write(1,a,n);}

```

Try it online!

*Saved ~~2~~ 9 bytes with an idea from Johan du Toit!!!*
*Added 4 bytes to fix a bug*

Inputs a pointer to the number and the number's length in bytes (since pointers in C carry no length info).
Outputs the message to `stdout`.

# Answer
> 7 votes
# jq, 40 bytes

```
[while(.>0;./256%.)%256]|reverse|implode

```

Try it online!

-6 bytes from ovs.

# Answer
> 6 votes
# Ruby, ~~26~~ 22 bytes

-4 bytes thanks to Dingus!

If we can take input as a hex string, the `"%x"%` can be removed.

```
->s{["%x"%s].pack'H*'}

```

Try it online!

The arbitrary base conversion builtin *Integer#digits* returns the digits in reverse order, which isn't helpful here:

```
->s{s.digits(256).reverse.pack'C*'}

```

Try it online!

# Answer
> 6 votes
# Python 2, 31 bytes

Not very interesting, but there conveniently a direct builtin.

```
lambda n:('%x'%n).decode('hex')

```

Try it online!

# Python 3, 28 bytes

`str.decode('hex')` no longer exists in Python 3, but is replaced with a similar `b''.fromhex`.

```
lambda n:b''.fromhex('%x'%n)

```

Try it online!

# Answer
> 5 votes
# Python 3, 39 bytes

```
f=lambda n:n and f(n>>8)+chr(n%256)or''

```

Try it online!

*-2 bytes thanks to ovs*

# Answer
> 5 votes
# JavaScript (Node.js), 37 bytes

Expects a BigInt.

```
f=n=>n?f(n>>8n)+Buffer([[n&255n]]):''

```

Try it online!

Or **33 bytes** without BigInt support (i.e. limited to 32-bit integers):

```
f=n=>n?f(n>>8)+Buffer([n&255]):''

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 3 bytes

```
₁вç

```

Basically the same approach as @*emanresuA*'s Vyxal answer, with integer as input.

Try it online or verify all test cases.

**Explanation:**

```
₁в   # Convert the (implicit) input-integer to base-256 as list
  ç  # Convert each integer in this list to a character with this codepoint
     # (after which the resulting list of characters is output implicitly)

```

# Answer
> 4 votes
# Jelly, 3 bytes

```
b⁹Ọ

```

Try it online!

Same as @emanresu’s Vyxal answer but in Jelly, so be sure to upvote that one too!

# Answer
> 3 votes
# Japt `-P`, ~~6~~ 5 bytes

```
ìG²od

```

Try it

```
ìG²od     :Implicit input of integer
ì         :Convert to digit array in base
 G        :  16
  ²       :  Squared
   o      :  Range [0,G²)
    d     :  Characters at those codepoints
          :Implicitly join and output

```

# Answer
> 1 votes
# Postscript, 23 bytes for hex input, 105 for decimal

The normal way to get a Postscript program to parse arbitrary formats is to concatenate the parser program and the input and send them to the interpreter. That's what I've done for the "no cheating" solutions.

I've set up TIO in Bash to put the program in the code section and the message in the input section. The header and footer arrange to concatenate the two and pass them to the interpreter. In the case of binary encoding, TIO's character count is wrong (it expects UTF-8 but we've got hex) so the header puts a line in the debug window with the correct count.

## Hex input, no binary encoding, no cheating, 64 bytes

```
{currentfile 9 string readhexstring exch print not{exit} if}loop

```

Try it online!

There's nothing clever here. `readhexstring` does the heavy lifting. The `9` is arbitrary, any size will work.

TIO counts the code as 64 bytes, but it will be mandatory to have whitespace between the program and the concatenated input string. I'm not sure if that should be counted.

If we're prepared to put a limit on the maximum size of the input message then we can make this smaller:

```
{currentfile 999999 string readhexstring pop print}exec

```

As shown, the limit could be sufficiently high that it's not a problem in practice. However, the question explicitly says no limit, so I won't persue this any further.

## Hex input, binary encoding, no cheating, 23 bytes

```
7b 92 1f 39 92 a5 92 7c 92 3e 92 76 92 70 7b 92
40 7d 92 54 7d 92 65

```

Try it online!

This is a straight binary encoding of the preceding solution. Unlike the non-binary-encoded version, no whitespace is needed between the program and the input.

## Hex input, no binary encoding, cheating, 7 bytes

If we're prepared to allow non-standard ways of passing the input, then we can use Postscript's hex string literals to do all the work. This involves sending character "\<", then the hex coding of the input, and finally "\>print". This is 7 bytes more than the original message.

```
<the message in hex goes here>print

```

Try it online!

Because the message and the program are interleaved, TIO can't count the program characters.

## Hex input, binary encoding, cheating, 4 bytes

And, of course there's the binary encoded version of the cheating method where we replace print with its binary encoding `\x92\x76`. This means adding just four bytes to the message being decoded.

```
<the message in hex goes here>\x92v

```

Try it online!

Note that TIO's bash input insists on UTF-8 encoding its input which mangles the `\x92` into two characters so I've used `iconv` in the header to undo that.

## Decimal input, no binary encoding, no cheating, 202 bytes

There's a discussion in the comments about whether hex should be allowed. For Postscript, this makes a big difference.

Postscript doesn't have any big integer handling. Integer limits are implementation dependent but you can't reliably expect anything longer than 32 bits to work. For hex, the input can be processed in arbitrary chunks. For decimal, we need to convert manually. This makes it a much more interesting problem.

The best I have so far is:

```
[[]{{currentfile read{48 sub exch{10 mul add
dup 256 mod exch -8 bitshift}forall
dup 0 eq {pop} if][exch}{exit}ifelse}loop
dup length 1 sub -1 0{2 copy get 1 string
dup 0 4 3 roll put print pop}for}exec

```

Try it online!

Note that this leaves two objects on the stack. As with the earlier non-binary-encoded answer there needs to be whitespace between the program and the input.

This requires a lot more explanation:

```
% Our state when we're parsing the input integer is to have two elements
% on the stack, a mark (which we'll use later) and an array containing the
% integer so far in base 256, least-significant digit first.
%
% When we read a digit, we multiply the values in the array by ten modulo
% 256 overflowing into the next digit.
%
% The code won't deal with characters that aren't decimal digits, so you
% have to be very careful setting up the input to avoid whitespace creeping
% in (including a newline at the end). Adding code to deal with this adds 38
% characters to the minimised version.
[ []             % Initialise the stack with mark and zero
{                % Start of exec (so we don't start parsing till the whole
                 % program has been loaded)
    {            % Start of the per-input-digit loop
        currentfile read    % Read one character from the input
        {                   % True path: we read a character
            48 sub          % Convert ASCII digit to decimal ('5' -> 5)
            exch            % Now have: mark new-digit array-of-current-total
            {               % Start of per-existing-digit loop
                % Stack: mark already-processed-digits adder next-digit
                10 mul      % Multiply the existing base-256 digit by ten
                add         % Add new input digit (first pass) or overflow
                dup         % Need the result twice: new digit and overflow
                256 mod exch % New digit
                -8 bitshift % Overflow
                % Stack: mark already-processed-digits adder=overflow
            } forall        % End of per-existing-digit loop
            dup 0 eq {pop} if % If the last overflow was zero, discard it
                            % We don't want lots of zeros at the top
            ]               % Use the mark on the stack to reform the array
            [ exch          % Replace the mark below the array
        }
        {exit} ifelse       % False path: end of file encountered
    } loop                  % End of input processing
    % We now have an array with the input converted to base 256
    % We can't use forall on this as that would start with the
    % least-significant digit and we need to start at the top. So, we'll
    % use a count-down for loop to access the array elements.
    dup length 1 sub -1 0
    {  % Start of per-character output loop
       % To convert to a character we put the digit into a 1 character string
        % For the next bit, "1 index exch" is neater than "2 copy ... pop"
        % but the latter is two characters shorter in non-binary encoding.
        % In binary, they're the same length.
                            % Stack: mark base-256-array index
        2 copy              % Stack: mark array index array index
        get                 % Stack: mark array index digit
        1 string dup 0      % Stack: mark array index digit string string 0
        4 3 roll            % Stack: mark array index string string 0 digit
        put                 % Stack: mark array index string
        print               % Print the converted character
        pop                 % Lose the duplicated index
    } for % End of per-character output loop
} exec

```

It feels like it should be possible to golf this down to something shorter.

## Decimal input, binary encoding, no cheating, 105 bytes

```
5b 5b 5d 7b 7b 92 1f 92 7b 7b 34 38 92 a9 92 3e
7b 31 30 92 6c 92 01 92 38 32 35 36 92 6a 92 3e
2d 38 92 0f 7d 92 49 92 38 30 92 3d 7b 92 75 7d
92 54 5d 5b 92 3e 7d 7b 92 40 7d 92 55 7d 92 65
92 38 92 62 20 31 92 a9 2d 31 20 30 7b 32 92 19
92 4b 31 92 a5 92 38 30 88 04 33 92 87 92 78 92
76 92 75 7d 92 48 7d 92 3f

```

Try it online!

This is a straight binary encoding of the preceding solution. No whitespace is needed between the program and the input.

# Answer
> 1 votes
# Charcoal, 8 bytes

```
⭆↨Ｎ²⁵⁶℅ι

```

Try it online! Link is to verbose version of code. Prefers to input a decimal integer, but you can make Charcoal accept hexadecimal by prefixing `[0x` and suffixing `]` as per the linked example. Explanation:

```
  Ｎ         Input as an integer
 ↨ ²⁵⁶      Convert to base 256
⭆           Map over values and join
       ι    Current value
      ℅     Convert to ASCII character
            Implicitly print

```

---
Tags: code-golf
---


# Question
Title: How many Jimmies does this platform need?
Platforms are stretches of `-` characters separated by one or more  characters.

For example:

```
------ --    ------ -

```

The above has 4 platforms sizes 6, 2, 6 and 1.

Platforms that are not supported will fall. To be supported platforms need Jimmies.

Jimmies look like this:

```
\o/

```

They are three units wide. Don't ask me what supports Jimmies.

Jimmies go under platforms to support them:

```
------------------
\o/  \o/  \o/  \o/

```

Each platform has a "center" of mass which is the average position of all its `-`s. (Or the average of the start and end.)

A platform is supported by Jimmies if its center of mass is between two points of the platform above a Jimmy or exactly above part of a Jimmy.

For example:

```
-----
 \o/

```

The above platform is supported because the center of mass is in a place the Jimmy is touching.

```
----------------
  \o/        \o/

```

The above platform is also supported because its center of mass is between the two Jimmies.

```
----
 \o/

```

In the above example the center of mass is between the Jimmy's hand and the Jimmy's head and thus the platform is supported by that Jimmy.

The following platform is not supported:

```
----
  \o/

```

This is because its center of mass is not directly above any part of the Jimmy and there is no Jimmy to the left.

A Jimmy can help support multiple platforms:

```
------- -------------
\o/   \o/           \o/

```

Your task is to take as input platforms (consisting only of `-`s and s). And output the minimum number of Jimmies required to support all the platforms given.

This is so answers will be scored in bytes with fewer bytes being better.

## Test cases

Each line has the input, `>` and then the output. Below I have added one way to place the Jimmies to support the platforms. This is neither part of the input nor output, it's just there for your convenience.

```
-------------------------------- > 1
              \o/
--------------- ---------------- > 2
      \o/              \o/
- ---------------------------- - > 2
\o/                          \o/
-  --------------------------- - > 3
\o/\o/                       \o/
--- - ------------------------ - > 3
\o/ \o/                      \o/
- ------------- -------------- - > 3
\o/           \o/            \o/
--------------- - -------------- > 3
      \o/       \o/          \o/
- - -  ------------------------- > 3
\o/ \o/           \o/

```

# Answer
# Jelly,  ~~18 13~~  10 bytes

```
ḲẈṣ0H«1§ĊS

```

A monadic Link that accepts a list of characters and yields an integer.

**Try it online!**

### How?

Jimmies can't help if the gap is greater than one, so the result is the sum of Jimmies required for each section after partitioning at such gaps. In each section, we need one Jimmy per platform minus one Jimmy for every two length-one platforms, since then Jimmies can share the load of these and any intermediate platforms.

```
ḲẈṣ0H«1§ĊS - Link: list of characters, P
Ḳ          - split at spaces
 Ẉ         - length of each -> lengths of platforms with zeros between sections
  ṣ0       - split at zeros -> list of section platform lengths
                               (potentially including phantom empty sections)
    H      - halve (vectorises)
     «1    - minimum with one (vectorises)
       §   - sums
        Ċ  - ceiling (vectorises)
         S - sum

```
> 12 votes

# Answer
# ARM T32 machine code, 32 bytes

```
0003 2000 2102 1e4a bf58 07d1 0fc9 3905
3102 f150 0000 cb04 2a20 d0f4 d8f8 4770

```

Following the AAPCS, this takes in r0 the address of the input as a null-terminated string *in UTF-32* (if this is not allowed, +2 bytes for `LDMIA``LDRB` with writeback or 2 instructions), and returns the number of Jimmies needed in r0.

The problem can be solved by a greedy algorithm, reading the string one character at a time while maintaining some values: \\$L\\$, the length so far of the current platform or 0 if none; \\$Z\\$, a flag that is 1 if the current platform is supported at its left end, and 0 otherwise; and \\$T\\$, the number of Jimmies used so far.

When reading a platform character (`-`), if \\$Z\\$ is 0, we need to add a Jimmy (incrementing \\$T\\$) the first time (when \\$L\\$ is 0); if \\$Z\\$ is 1 (left-supported), we only need to add a Jimmy if the platform is longer than 1, so increment \\$T\\$ on the second platform character (when \\$L\\$ is 1). These cases can be combined: increment \\$T\\$ if \\$L = Z\\$. Afterwards, \\$L\\$ is incremented.

When reading a non-platform character (), the way \\$Z\\$ is modified is more complicated. For a long platform (\\$L \ge 2\\$), if the platform is not left-supported, its Jimmy supports only that platform, whereas if it is left-supported, its second Jimmy can be placed at its right end to potentially support a later platform; this means that \\$Z\\$ remains unchanged. For a short platform (\\$L\\$ is 1), an existing left-support is enough for it, while if it was not left-supported, then it gets a new Jimmy that can also support a later platform; this means that \\$Z\\$ is inverted. Finally, if there is no platform between two consecutive non-platform characters (\\$L\\$ is 0), then any out-hanging Jimmy runs out; \\$Z\\$ is set to 0. Afterwards, \\$L\\$ is set to 0. Here is a summary of the way \\$Z\\$ is changed: $$ \begin{array}{c|ccccc} & 0 & 1 & 2 & 3 & \cdots \\ \hline 0 & 0 & 1 & 0 & 0 & \cdots \\ 1 & 0 & 0 & 1 & 1 & \cdots \end{array} $$

In my program, \\$L\\$ and \\$Z\\$ are combined into a single value \\$K = 2L - Z - 2\\$.
Then, when reading a platform character (`-`), \\$K\\$ is increased by 2, and \\$T\\$ is incremented if \\$K\\$ changes from -2 to 0 or from -1 to 1, or equivalently, if \\$K\\$ changes from negative to nonnegative. When reading a non-platform character (), \\$K\\$ changes as follows: $$ \begin{array}{c|cccc|ccccc} \textrm{Before} & -3 & -2 & -1 & 0 & 1 & 2 & 3 & 4 & \cdots \\ \hline \textrm{After} & -2 & -2 & -2 & -3 & -3 & -2 & -3 & -2 & \cdots \end{array} $$

Assembly:

```
.code 16
.section .text
.syntax unified
.global njimmies
.thumb_func
njimmies:
    movs r3, r0       @ Transfer string address to r3
    movs r0, #0       @ Total number of Jimmies = 0
    movs r1, #2       @ K = 2 (will be changed by the following code before reading the string)
space:
    subs r2, r1, #1   @ Calculate K-1
    it pl             @ If the result is nonnegative...
    lslpl r1, r2, #31 @  shift the low bit of the result into the high bit of r1
    lsrs r1, r1, #31  @ Shift the high bit of r1 into the low bit; all other bits become 0
    subs r1, #5       @ Make the value -4 or -5, and fall through
platform:
    adds r1, #2       @ Add 2 to K
    adcs.w r0, #0     @ Count up one Jimmy if K went from negative to nonnegative
    ldmia r3!, {r2}   @ Load the next character
    cmp r2, #32
    beq space         @ Jump on ' '
    bhi platform      @ Jump on '-'
    bx lr             @ Return on the null terminator

```
> 8 votes

# Answer
# Jelly, ~~21~~ ~~20~~ 19 bytes

```
OḂŒrµ=1EƇṣØ0Ẉ:2SạSḢ

```

Try it online!

This may or may not be an incredibly stupid way to do it.

Based on the following observation: the best way is to use one Jimmy per platform, unless there are two platforms of length 1 such that all spaces between them are also length 1, in which case they can be connected by Jimmies, saving one Jimmy.
> 7 votes

# Answer
# C (clang), 73 bytes

```
c;o;f(*s){for(c=o=1;*s;o=*s++)c=o-*s?*s%5?s[1]%5>0|c:s[1]%2-~c:c;*s=c/2;}

```

Try it online!

-7 byte thanks to ceilingcat!!
> 5 votes

# Answer
# APL (Dyalog Unicode), 29 bytes

```
{+/⌈+/¨1⌊2÷⍨0(≠⊆⊢)≢¨⍵⊆⍨' '≠⍵}

```

Try it online!
> 4 votes

# Answer
# , ~~109~~ ~~93~~ 92 bytes

Or **\>=4.1, 78 bytes** by replacing two `function` appearances with `\`s.

```
function(x,`+`=strsplit,`?`=sum)?sapply(el(x+"  ")+" ",function(a)pmin(nchar(a)/2,1)?.5)%/%1

```

Try it online!

Port of @Jonathan Allan's solution.
> 4 votes

# Answer
# Python 3, ~~88~~ ~~81~~ ~~79~~ 77 bytes

```
lambda x:-sum(-sum(min(len(j),2)for j in i.split())//2for i in x.split('  '))

```

Try it online!

-7 bytes thanks to EnderShadow8 and movatica.
-2 bytes thanks to movatica.
-2 bytes thanks to Wheat Wizard.

Based on Jonathan Allan's answer. Outputs an integer.
> 3 votes

# Answer
# JavaScript (V8), ~~86~~ 78 bytes

Thanks Johan du Toit for -8

```
x=>(a=.5,x.split`  `.map(p=>p.split` `.map(i=>a+=i?i[1]?1:.5:0,a=~~a+.5)),~~a)

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 12 bytes

```
ð¡€g0¡<Ā>;OîO

```

Port of *@JonathanAllan*'s Jelly answer.

Try it online or verify all test cases.

**Explanation:**

```
ð¡             # Split the (implicit) input-string on spaces
               # (`#` doesn't work here if the input lacks any spaces)
  €g           # Get the length of each part
    0¡         # Split this list of integers on 0s
      <        # Decrease each length by 1
       Ā       # Check which values are NOT 0 (0 if 0; 1 if >= 1)
        >      # Increase each by 1 (1 if 0; 2 if >= 1)
         ;     # Halve each (0.5 if 0; 1 if >= 1)
          O    # Sum each inner list
           î   # Ceil each sum
            O  # And sum those together again
               # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Retina, 12 bytes

```
--+
--
- ?-?

```

Try it online!

Reduce all long platforms to length 2, which doesn't change the result. Now each Jimmy can support up to two `-`s close together. Count such pairs of `-`s and excess single `-`s.
> 3 votes

# Answer
# ///, 31 bytes

```
/---/--//- -/--//--/1//-/1// //

```

Input should be appended to the program, as permitted here. Output is in unary.

Try it online!

This uses the same idea as one of my other answers – reduce all long platforms to length 2, which doesn't change the result, and then each Jimmy can support up to two `-`s close together – but does it in a somewhat more complicated way.

```
                                Example string: "- --- -  ---- -"
/---/--/    Reduce long platforms to length 2   "- -- -  -- -"
/- -/--/    Close short gaps                    "----  ---"
/--/1/      Count pairs of -s                   "11  1-"
/-/1/       Count leftover single -s            "11  11"
/ //        Remove spaces                       "1111"

```
> 2 votes

# Answer
# Charcoal, ~~21~~ 19 bytes

```
ＩΣＥ⪪Ｓ  ⌈⊘ΣＥ⪪ι ⌊⟦²Ｌλ

```

Try it online! Link is to verbose version of code. Explanation: Now a port of @Yousername's answer.

```
    Ｓ               Input string
   ⪪                Split on pairs of spaces
  Ｅ                 Map over runs
           ⪪ι       Split run on spaces
          Ｅ         Map over each platform
                 Ｌλ Length of platform
              ⌊⟦²   Minimum of that and 2
         Σ          Take the sum
        ⊘           Halved
       ⌈            Ceiling
 Σ                  Take the sum
Ｉ                   Cast to string
                    Implicitly print

```
> 0 votes

---
Tags: code-golf
---